package presenseredis

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/AFASystems/presence/internal/pkg/model"
	"github.com/redis/go-redis/v9"
)

func LoadBeaconsList(client *redis.Client, ctx context.Context) map[string]model.Beacon {
	beaconsList, err := client.Get(ctx, "beaconsList").Result()
	beaconsMap := make(map[string]model.Beacon)

	if err == redis.Nil {
		fmt.Println("no beacons list, starting empty")
	} else if err != nil {
		fmt.Println("no connection to redis")
	} else {
		json.Unmarshal([]byte(beaconsList), &beaconsMap)
	}

	return beaconsMap
}

func LoadLatestList(client *redis.Client, ctx context.Context) map[string]model.Beacon {
	latestList, err := client.Get(ctx, "latestList").Result()
	latestMap := make(map[string]model.Beacon)

	if err == redis.Nil {
		fmt.Println("no beacons list, starting empty")
	} else if err != nil {
		fmt.Println("no connection to redis")
	} else {
		json.Unmarshal([]byte(latestList), &latestMap)
	}

	return latestMap
}

func LoadSettings(client *redis.Client, ctx context.Context) model.SettingsVal {
	redisSettings, err := client.Get(ctx, "settings").Result()
	var settings model.SettingsVal

	if err == redis.Nil {
		fmt.Println("no beacons list, starting empty")
	} else if err != nil {
		fmt.Println("no connection to redis")
	} else {
		json.Unmarshal([]byte(redisSettings), &settings)
	}

	return settings
}

func SaveBeaconsList(appCtx *model.AppContext, client *redis.Client, ctx context.Context) {
	appCtx.Beacons.Lock.Lock()
	data, _ := json.Marshal(appCtx.Beacons.Beacons)
	appCtx.Beacons.Lock.Unlock()

	err := client.Set(ctx, "beaconsList", data, 0).Err()
	if err != nil {
		fmt.Println("error in saving to redis: ", err)
	}
}

func SaveLatestList(appCtx *model.AppContext, client *redis.Client, ctx context.Context) {
	appCtx.LatestList.Lock.Lock()
	data, _ := json.Marshal(appCtx.LatestList.LatestList)
	appCtx.LatestList.Lock.Unlock()

	err := client.Set(ctx, "latestList", data, 0).Err()
	if err != nil {
		fmt.Println("error in saving to redis: ", err)
	}
}

func SaveSettings(appCtx *model.AppContext, client *redis.Client, ctx context.Context) {
	appCtx.Settings.Lock.Lock()
	data, _ := json.Marshal(appCtx.Settings.Settings)
	appCtx.Settings.Lock.Unlock()

	err := client.Set(ctx, "settings", data, 0).Err()
	if err != nil {
		fmt.Println("error in saving to redis: ", err)
	}
}
