package cache

import (
	"github.com/go-redis/redis"
	"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"
)

// 将token存入到redis中
func SetToken(uid string, uuid string) {
	Redis.Set("login:"+uid, uuid, time.Hour*1)
}

// 从redis中取出token
func GetToken(uid string) (string, error) {
	return Redis.Get("login:" + uid).Result()
}
