package scene

import (
	"context"
	"fmt"
	"github.com/gogf/gf/database/gredis"
)

const (
	scenePrefix = "scene:"
	dataExpires = 7200
)

type GetSceneParams struct {
	Type       string `json:"type"`
	Name       string `json:"name"`
	DeviceCode string `json:"device_code"`
}

type InfoScene struct {
	Id         string `json:"id"`
	Name       string `json:"name"`
	Status     int    `json:"status"`
	Action     string `json:"action"`
	Desc       string `json:"desc"`
	SceneType  string `json:"scene_type"`
	DeviceType string `json:"device_type"`
	Config     string `json:"config"`
	Time       string `json:"time"`
}

type Info struct {
	Key     string `json:"key"`
	SceneId string `json:"scene_id"`
	TaskId  string `json:"task_id"`
	Config  string `json:"config"`
}

type Manager struct {
	redisClient *gredis.Redis
	ctx         context.Context
}

func NewSceneManager(host string, port int) *Manager {
	red := gredis.New(&gredis.Config{
		Host:      host,
		Port:      port,
		Db:        2,
		MaxActive: 100,
	})
	ctx := context.Background()
	helper := &Manager{
		redisClient: red,
		ctx:         ctx,
	}
	return helper
}

func (a *Manager) SaveScene(info *Info) error {
	_, err := a.redisClient.DoVar("SET", info.Key, info.Config)
	if err != nil {
		return err
	}
	_, err = a.redisClient.Do("EXPIRE", info.Key, 0)
	if err != nil {
		return err
	}
	return nil
}

func (a *Manager) GetScene(key string) (string, error) {
	// get status from redis
	result, err := a.redisClient.DoVar("GET", key)
	if err != nil {
		return "", err
	}
	return result.String(), nil
}

func (a *Manager) DeleteScene(key string) error {
	// get status from redis
	_, err := a.redisClient.Do("DEL", key)
	if err != nil {
		return err
	}
	return nil
}

// GetAllScenes 查询所有场景信息s
func (a *Manager) GetAllScenes() ([]*InfoScene, error) {
	// 使用KEYS命令获取所有匹配前缀的键s
	keys, err := a.redisClient.DoVar("KEYS", scenePrefix+"*")
	fmt.Printf("使用KEYS命令获取所有匹配前缀的键%v", keys)
	if err != nil {
		return nil, err
	}

	// 检查是否有数据
	if keys.IsEmpty() {
		return nil, nil
	}

	// 转换为字符串切片
	keyList := keys.Strings()

	// 存储所有结果
	scenes := make([]*InfoScene, 0)
	var scene InfoScene
	for _, key := range keyList {

		result, err := a.redisClient.DoVar("GET", key)
		if err != nil {
			return nil, err
		}
		err = result.Struct(&scene)
		if err != nil {
			return nil, err
		}
		scenes = append(scenes, &scene)
	}

	return scenes, nil
}
