package scene

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

const (
	timerScenePrefix   = "scene:timer:*"
	deviceScenePrefix  = "scene:device_status:*"
	weatherScenePrefix = "scene:weather:*"
	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"`
	Key           string    `json:"key"`
	Name          string    `json:"name"`
	SceneType     string    `json:"scene_type"`
	ActionDesc    string    `json:"action_desc"`
	ConditionDesc string    `json:"condition_desc"`
	SceneId       string    `json:"scene_id"`
	Config        string    `json:"config"`
	Status        int       `json:"status"`
	Time          time.Time `json:"time"`
}

type AllSceneResult struct {
	Total int          `json:"total"`
	Data  []*InfoScene `json:"data"`
}

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 *InfoScene) error {
	_, err := a.redisClient.DoVar("SET", info.Key, info)
	if err != nil {
		return err
	}
	//_, err = a.redisClient.Do("EXPIRE", info.Key, -1)
	//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
}

// GetAllScenesPage 查询定时场景
func (a *Manager) GetAllScenesPage(code string, pi, ps int) (AllSceneResult, error) {
	var key string
	switch code {
	case "timer":
		key = timerScenePrefix
	case "device":
		key = deviceScenePrefix
	case "weather":
		key = weatherScenePrefix
	default:
		key = scenePrefix
	}

	var result AllSceneResult
	// 使用KEYS命令获取所有匹配前缀的键s
	keys, err := a.redisClient.DoVar("KEYS", key)
	if err != nil {
		return result, err
	}

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

	var start, end int
	// 转换为字符串切片
	keyList := keys.Strings()
	result.Total = len(keyList)
	if len(keyList) > 0 {
		start = (pi - 1) * ps
		end = pi*ps - 1
		if end > len(keyList)-1 {
			end = len(keyList) - 1
		}
	}
	// 存储所有结果
	for i := start; i <= end; i++ {
		scene := new(InfoScene)
		r, err := a.redisClient.DoVar("GET", keyList[i])
		if err != nil {
			return result, err
		}
		err = r.Struct(&scene)
		if err != nil {
			return result, err
		}
		result.Data = append(result.Data, scene)
	}
	return result, nil
}

// GetAllScenes 查询定时场景
func (a *Manager) GetAllScenes(code string) ([]*InfoScene, error) {
	var key string
	switch code {
	case "time":
		key = timerScenePrefix
	case "device":
		key = deviceScenePrefix
	case "weather":
		key = weatherScenePrefix
	default:
		key = scenePrefix
	}

	// 使用KEYS命令获取所有匹配前缀的键s
	keys, err := a.redisClient.DoVar("KEYS", key)
	if err != nil {
		return nil, err
	}
	// 检查是否有数据
	if keys.IsEmpty() {
		return nil, nil
	}

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

	// 存储所有结果
	scenes := make([]*InfoScene, 0)
	for _, v := range keyList {
		scene := new(InfoScene)
		r, err := a.redisClient.DoVar("GET", v)
		if err != nil {
			return nil, err
		}
		err = r.Struct(&scene)
		if err != nil {
			return nil, err
		}
		scenes = append(scenes, scene)
	}
	return scenes, nil
}
