package main

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

	"github.com/redis/go-redis/v9"
)

type Per struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

type Beacon struct {
	ID   string `json:"id"` // Use JSON tags to ensure correct field names
	Type string `json:"type"`
	Temp int    `json:"temp"`
	Name string `json:"name"`
}

func ConvertStructToMap(obj any) (map[string]any, error) {
	// 1. Marshal the struct into a JSON byte slice
	data, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}

	// 2. Unmarshal the JSON byte slice into the map
	var result map[string]any
	err = json.Unmarshal(data, &result)
	if err != nil {
		return nil, err
	}

	return result, nil
}

// func main() { ... }
// client.HSet(ctx, "beacon:123", resultMap).Err()

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "127.0.0.1:6379",
		Password: "",
	})

	ctx := context.Background()

	err := client.Set(ctx, "testkey", "hello world", 0).Err()
	if err != nil {
		fmt.Println("Ok")
	}

	val, err := client.Get(ctx, "testkey").Result()
	if err != nil {
		fmt.Println("Ok")
	}
	fmt.Println(val)

	err = client.SAdd(ctx, "myset", "b-1").Err()
	if err != nil {
		fmt.Println(err)
	}

	res, err := client.SMembers(ctx, "myset").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("res1: ", res)

	err = client.SAdd(ctx, "myset", "b-2").Err()
	if err != nil {
		fmt.Println(err)
	}

	res, err = client.SMembers(ctx, "myset").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("res1: ", res)

	err = client.SAdd(ctx, "myset", "b-1").Err()
	if err != nil {
		fmt.Println(err)
	}

	res, err = client.SMembers(ctx, "myset").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("res1: ", res)
	fmt.Println("type: ", reflect.TypeOf(res))

	// b := Beacon{
	// 	ID:   "hello",
	// 	Type: "node",
	// 	Temp: 10,
	// 	Name: "Peter",
	// }

	// per := Per{
	// 	Name: "Janez",
	// 	Age:  10,
	// }

	// bEncoded, err := ConvertStructToMap(b)
	// if err != nil {
	// 	fmt.Print("error\n")
	// }

	// perEncoded, err := ConvertStructToMap(per)
	// if err != nil {
	// 	fmt.Print("error\n")
	// }

	// err = client.HSet(ctx, "myhash", bEncoded).Err()
	// fmt.Println(err)

	// res, _ := client.HGetAll(ctx, "myhash").Result()
	// fmt.Println(res)

	// err = client.HSet(ctx, "myhash", perEncoded).Err()
	// fmt.Println(err)

	// res, _ = client.HGetAll(ctx, "myhash").Result()
	// fmt.Println(res)

}
