package config

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
)

const (
	TokenExpireTime = 3 * time.Hour
)

var (
	TokenRedis *redis.Client
)

func InitRedis() {
	TokenRedis = newRedis(os.Getenv("TOKEN_REDIS_ADDR"), os.Getenv("TOKEN_REDIS_PW"), os.Getenv("TOKEN_REDIS_DB"))
}

func newRedis(addr, password, db string) (client *redis.Client) {
	db2, _ := strconv.ParseUint(db, 10, 64)
	client = redis.NewClient(&redis.Options{
		Addr:       addr,
		Password:   password,
		DB:         int(db2),
		MaxRetries: 1,
	})

	if _, err := client.Ping().Result(); err != nil {
		logrus.Panicf("连接Redis[%v]不成功, err:%+v", addr, err)
	}
	return
}

func GetUserTokenKey(uid int64) string {
	return fmt.Sprintf("token:%v", uid)
}

func GetTokenKey(t string) string {
	return fmt.Sprintf("token:%v", t)
}
