package Account

import (
	"ColdVerify_local/conf"
	"fmt"
	"github.com/astaxie/beego/cache"
	_ "github.com/astaxie/beego/cache/redis"
	uuid "github.com/satori/go.uuid"
	"time"
)

var redisCache_Tokey cache.Cache

func init() {
	//注册模型
	//orm.RegisterModel(new(Tokey))

	config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
		"redis_Tokey", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
	fmt.Println(config)
	var err error
	redisCache_Tokey, err = cache.NewCache("redis", config)
	if err != nil || redisCache_Tokey == nil {
		errMsg := "failed to init redis"
		fmt.Println(errMsg, err)
	}
}

// ---------------- Redis -------------------
//Redis_Set(m.T_sn,m) // Redis 更新缓存
func Redis_Tokey_Set(key string, r string) (err error) {
	err = redisCache_Tokey.Put(key, r, 24*time.Hour)
	if err != nil {
		fmt.Println("set key:", key, ",value:", r, err)
	}
	return
}

//if r,is :=Redis_Get(T_sn);is{
//return r,nil
//}
func Redis_Tokey_Get(key string) (r string, is bool) {
	if redisCache_Tokey.IsExist(key) {
		//println("找到key:",key)
		v := redisCache_Tokey.Get(key)
		value := string(v.([]byte))
		return value, true
	}
	//println("没有 找到key:",key)
	return "", false
}

func Redis_DelK(key string) (err error) {
	err = redisCache_Tokey.Delete(key)
	return
}

// ---------------- 特殊方法 -------------------

// 验证 TOKEY
func Read_Tokey(User_tokey string) (string, bool) {

	return Redis_Tokey_Get(User_tokey)
}

// 添加 Tokey
func Add_Tokey(User_uuid string) (Tokey string) {

	for true {
		Tokey = uuid.NewV4().String()
		_, is := Redis_Tokey_Get(Tokey)
		if !is {
			break
		}
		fmt.Print("申请 TOKEY 重复！重新生成。", Tokey)
	}
	Redis_Tokey_Set(Tokey, User_uuid)

	return Tokey
}

