package redismgr

import (
	"server/conf"
	"time"

	"github.com/gomodule/redigo/redis"
	"github.com/name5566/leaf/log"
)

var (
	pool *redis.Pool
)

func init() {
	Connect()
}

// Connect 初始化连接池
func Connect() {
	pool = &redis.Pool{
		MaxIdle:     256,              // 最大空闲连接数
		MaxActive:   0,                // 最大连接数，0表示不限制
		IdleTimeout: time.Second * 60, // 空闲超时时间
		Dial: func() (redis.Conn, error) {
			return redis.Dial(
				"tcp",
				conf.RedisDBAddr,
				redis.DialPassword(""), // 如果有密码
				redis.DialDatabase(0),  // 选择数据库
			)
		},
	}
	log.Release("redis Connect success")
}

// GetPool 获取连接池
func GetPool() *redis.Pool {
	return pool
}

// Set 设置键值对
func Set(key string, value interface{}, expiration ...int) error {
	conn := pool.Get()
	defer conn.Close()

	if len(expiration) > 0 {
		_, err := conn.Do("SETEX", key, expiration[0], value)
		return err
	}
	_, err := conn.Do("SET", key, value)
	return err
}

// Get 获取值
func Get(key string) (string, error) {
	conn := pool.Get()
	defer conn.Close()

	reply, err := redis.String(conn.Do("GET", key))
	if err == redis.ErrNil {
		return "", nil
	}
	return reply, err
}

// Delete 删除键
func Delete(key string) error {
	conn := pool.Get()
	defer conn.Close()

	_, err := conn.Do("DEL", key)
	return err
}

// Exists 检查键是否存在
func Exists(key string) (bool, error) {
	conn := pool.Get()
	defer conn.Close()

	return redis.Bool(conn.Do("EXISTS", key))
}

// HashSet 设置哈希表字段
func HashSet(key, field string, value interface{}) error {
	conn := pool.Get()
	defer conn.Close()

	_, err := conn.Do("HSET", key, field, value)
	return err
}

// HashGet 获取哈希表字段
func HashGet(key, field string) (string, error) {
	conn := pool.Get()
	defer conn.Close()

	reply, err := redis.String(conn.Do("HGET", key, field))
	if err == redis.ErrNil {
		return "", nil
	}
	return reply, err
}

// ListPush 将值推入列表
func ListPush(key string, value interface{}) error {
	conn := pool.Get()
	defer conn.Close()

	_, err := conn.Do("LPUSH", key, value)
	return err
}

// ListRange 获取列表范围内的元素
func ListRange(key string, start, stop int) ([]string, error) {
	conn := pool.Get()
	defer conn.Close()

	return redis.Strings(conn.Do("LRANGE", key, start, stop))
}

// 测试函数
func test() {
	// 测试字符串操作
	err := Set("test_key", "test_value", 60)
	if err != nil {
		log.Debug("Set error:", err)
	}

	value, err := Get("test_key")
	if err != nil {
		log.Debug("Get error:", err)
	}
	log.Debug("Get value:", value)

	// 测试哈希表操作
	err = HashSet("user:1001", "name", "player1")
	if err != nil {
		log.Debug("HashSet error:", err)
	}

	name, err := HashGet("user:1001", "name")
	if err != nil {
		log.Debug("HashGet error:", err)
	}
	log.Debug("HashGet name:", name)

	// 测试列表操作
	err = ListPush("game:list", "game1")
	if err != nil {
		log.Debug("ListPush error:", err)
	}

	games, err := ListRange("game:list", 0, -1)
	if err != nil {
		log.Debug("ListRange error:", err)
	}
	log.Debug("Games:", games)
}
