/*
 * @Author: ZXGoto
 * @Date: 2019-10-30
 */

package cache

import (
	"exhibitionCentre/config"
	"exhibitionCentre/logging"
	"fmt"
	"time"

	"github.com/gomodule/redigo/redis"
)

var (
	redisClient *Redis
)

// init - initializes the redis db
func init() {
	config := &RedisConfig{
		MaxIdle:            config.Config.Redis.MaxIdle,
		MaxActive:          config.Config.Redis.MaxActive,
		IdleTimeout:        time.Duration(config.Config.Redis.IdleTimeout),
		Address:            config.Config.Redis.Address,
		Password:           config.Config.Redis.Password,
		DialReadTimeout:    config.Config.Redis.DialReadTimeout,
		DialWriteTimeout:   config.Config.Redis.DialWriteTimeout,
		DialConnectTimeout: config.Config.Redis.DialConnectTimeout,
		DB:                 config.Config.Redis.Database,
	}
	redisClient = NewRedis(config)
	logging.Log.Info("初始化Redis完毕.")
}

// Close - closes the redis db
func Close() {
	if redisClient == nil {
		return
	}
	redisClient.Close()
	logging.Log.Info("Redis关闭.")
}

// Stats - gets redis stats
func Stats() *redis.PoolStats {
	if redisClient == nil {
		return &redis.PoolStats{}
	}
	stats := redisClient.Stats()
	return &stats
}

func CreateVerificationCode(email, code string) bool {
	if redisClient == nil {
		return false
	}
	key := fmt.Sprintf("verification_code:%s", email)
	return redisClient.MultiCreate(func(conn redis.Conn) {
		conn.Send("MULTI")
		conn.Send("SET", key, code)
		conn.Send("EXPIRE", key, 60*5)
	})
}

func GetVerificationCode(email string) string {
	if redisClient == nil {
		return ""
	}
	key := fmt.Sprintf("verification_code:%s", email)
	records, err := redis.Strings(redisClient.MultiGet(func(conn redis.Conn) {
		conn.Send("MULTI")
		conn.Send("GET", key)
	}))
	if err != nil {
		logging.Log.Errorf("获取数据失败: %s\n", err.Error())
		return ""
	}
	if len(records) > 0 {
		return records[0]
	}
	return ""
}

func DeleteVerificationCode(email string) bool {
	if redisClient == nil {
		return false
	}
	key := fmt.Sprintf("verification_code:%s", email)
	return redisClient.Delete(key)
}
