package storage

import (
	"fmt"
	"github.com/boltdb/bolt"
	"log"
)

type BoltSdk struct {
	bucket []byte
	db     *bolt.DB
}

func NewBoltSdk() *BoltSdk {
	db, err := bolt.Open("transcoder.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	bucket := []byte("transcoder")
	_ = db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists(bucket)
		if err != nil && err != bolt.ErrBucketExists {
			fmt.Println(err)
		}
		return err
	})
	return &BoltSdk{
		db:     db,
		bucket: bucket,
	}
}

func (s *BoltSdk) Set(key, value string) (err error) {
	err = s.db.Update(func(tx *bolt.Tx) error {
		bucket := tx.Bucket(s.bucket)
		if bucket == nil {
			return fmt.Errorf("bucket not found")
		}
		return bucket.Put([]byte(key), []byte(value))
	})
	return
}

func (s *BoltSdk) Get(key string) (value string, err error) {
	err = s.db.View(func(tx *bolt.Tx) error {
		bts := tx.Bucket(s.bucket).Get([]byte(key))
		value = string(bts)
		return nil
	})
	return
}

func (s *BoltSdk) GetFirst() (key, value string, err error) {
	err = s.db.Update(func(tx *bolt.Tx) error {
		cursor := tx.Bucket(s.bucket).Cursor()
		k, v := cursor.First()
		key = string(k)
		value = string(v)
		return nil
	})
	return
}

func (s *BoltSdk) Delete(key string) (err error) {
	err = s.db.Update(func(tx *bolt.Tx) error {
		return tx.Bucket(s.bucket).Delete([]byte(key))
	})
	return
}

func (s *BoltSdk) Close() error {
	return s.db.Close()
}
