package model

import (
	"crypto/sha256"
	"encoding/json"
	"fmt"
)

func (b *BeaconEvent) Hash() []byte {
	rBatt := (b.Battery / 10) * 10
	c := fmt.Sprintf("%d%d%s%s%s", rBatt, b.Event, b.ID, b.Name, b.Type)
	h := sha256.New()
	h.Write([]byte(c))
	bs := h.Sum(nil)

	return bs
}

func (b BeaconEvent) ToJSON() ([]byte, error) {
	eData, err := json.Marshal(b)
	if err != nil {
		return nil, err
	}
	return eData, nil
}

func convertStructToMap(obj any) (map[string]any, error) {
	data, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}

	var result map[string]any
	if err := json.Unmarshal(data, &result); err != nil {
		return nil, err
	}

	return result, nil
}

func (loc HTTPLocation) RedisHashable() (map[string]any, error) {
	return convertStructToMap(loc)
}

func (be BeaconEvent) RedisHashable() (map[string]any, error) {
	return convertStructToMap(be)
}
