package cache

import (
	"fmt"
	"github.com/go-redis/redis"
	"iot_manager_service/config"
	"iot_manager_service/util/common"
	"strconv"
	"time"
)

var Redis *redis.Client

func InitRedis() error {
	cfg := config.Instance()
	addr := cfg.Redis.Host

	fmt.Printf("addr = %v \n", addr)
	Redis = redis.NewClient(&redis.Options{
		Addr:         addr,
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     10,
		PoolTimeout:  30 * time.Second,
		Password:     cfg.Redis.Password,
		DB:           1, //指定 哪个数据库，不然找不到数据
	})
	_, err := Redis.Ping().Result()
	if err != nil {
		return err
	}
	return nil
}

const (
	DeviceStateKey = "dev_stat_"
	ONLINE         = "online"
	TLast          = "tlast"

	DeviceDataKey = "dev_data_"
	TIME          = "time"
)

//GetDeviceState 获取设备状态 1在线 2离线
func GetDeviceState(id string) (retTime time.Time, retState string) {
	defer func() {
		if err1 := recover(); err1 != nil {
			fmt.Println("GetDeviceState err = ", err1)
		}
	}()
	retTime = time.Time{}
	retState = "2"
	//redis中 1在线 0离线
	//todo 需要统一
	list, err := Redis.HMGet(DeviceStateKey+id, TLast, ONLINE).Result()
	//fmt.Printf("list = %v id=%v \n", list, DeviceStateKey+id)
	//fmt.Printf("err = %v \n", err)
	if err == nil && list[0] != nil || list[1] != nil {
		t, err1 := common.MlParseTime(list[0].(string))
		s, err0 := strconv.Atoi(list[1].(string))
		if err0 == nil && err1 == nil {
			if s == 1 {
				retState = "1"
			}
			retTime = t
		}
	}
	return
}

// GetSwitchState 查灯是否开关
func GetSwitchState(id string) bool {
	_, values := GetDeviceData(id)
	//fmt.Printf("id=%v  values = %v \n", id, values)
	value, ok := values[1]
	if ok && value > 1 {
		return true
	}
	return false
}

//GetDeviceData 获取设备数据 时间 key-value
func GetDeviceData(id string) (retTime time.Time, values map[int]float32) {
	values = make(map[int]float32)
	if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
		for k, v1 := range mapData {
			if k == TIME {
				if t, err := common.MlParseTime(v1); err == nil {
					retTime = t
				}
			} else {
				if sid, err := strconv.Atoi(k); err == nil {
					if val, err := strconv.ParseFloat(v1, 32); err == nil {
						values[sid] = float32(val)
					}
				}
			}
		}
	}
	return
}

// 取led信息屏
func GetDeviceLedData(id string) (values map[string]interface{}) {
	values = make(map[string]interface{})
	if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
		for k, v1 := range mapData {
			values[k] = (v1)
		}
	}
	return
}
