package persistence

import (
	"bytes"
	"encoding/gob"
	"log"

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

func LoadState(db *bolt.DB, ctx *model.AppContext) {
	err := db.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket(model.World)
		if bucket == nil {
			return nil
		}

		decode := func(key string, dest interface{}) {
			val := bucket.Get([]byte(key))
			if val == nil {
				return
			}
			buf := bytes.NewBuffer(val)
			if err := gob.NewDecoder(buf).Decode(dest); err != nil {
				log.Fatal("decode error: ", err)
			}
		}

		decode("beaconsList", &ctx.Beacons.Beacons)
		decode("buttonsList", &ctx.ButtonsList)
		decode("settings", &ctx.Settings)
		return nil
	})

	if err != nil {
		log.Fatal(err)
	}
}
