package persistence

import (
	"bytes"
	"encoding/gob"
	"fmt"

	"github.com/AFASystems/presence/internal/pkg/model"
	"github.com/boltdb/bolt"
)

func PersistBeacons(beacons *model.BeaconsList) error {
	buf := &bytes.Buffer{}
	enc := gob.NewEncoder(buf)
	if err := enc.Encode(beacons.Beacons); err != nil {
		fmt.Println("error in encoding: ", err)
		return err
	}

	key := []byte("beacons_list")
	err := model.Db.Update(func(tx *bolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists(model.World)
		if err != nil {
			fmt.Println("error in creating a bucket")
			return err
		}
		return bucket.Put(key, buf.Bytes())
	})

	return err
}

func PersistSettings(settings *model.Settings) error {
	buf := &bytes.Buffer{}
	enc := gob.NewEncoder(buf)
	if err := enc.Encode(settings); err != nil {
		return err
	}

	key := []byte("settings")
	err := model.Db.Update(func(tx *bolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists(model.World)
		if err != nil {
			return err
		}
		return bucket.Put(key, buf.Bytes())
	})

	return err
}
