package cache

import (
	"encoding/json"
	"github.com/go-redis/redis"
	"iot_manager_service/app/user/dao"
	"iot_manager_service/config"
	"time"
)

var Redis *redis.Client

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

	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"
)

// 将当前用户存入到redis中
func SetNowSysUser(uid string, user *dao.SysUser) {
	marshal, _ := json.Marshal(user)
	Redis.Set("login:"+uid, marshal, time.Hour*24*7)
}

// 从redis中取出当前用户
func GetNowSysUser(uid string) (*dao.SysUser, error) {
	result, _ := Redis.Get("login:" + uid).Result()
	str := []byte(result)
	nowuser := dao.SysUser{}
	err := json.Unmarshal(str, &nowuser)
	return &nowuser, err
}

// 将当前用户从redis中删除(退出登录)
func DeleteToken(uid string) error {
	return Redis.Del("login:" + uid).Err()
}

// 存储离线用户的消息
func StoreMessages(id, msg string) error {
	return Redis.LPush("offline:"+id, msg).Err()
}

// 获取用户的离线信息
func GetStoreMessages(id string) []string {
	result, _ := Redis.LRange("offline:"+id, 0, -1).Result()
	return result
}
