package service

import (
	"errors"
	"main/constant"
	"main/mt"
	"q5"
	"time"

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

type redisMap struct {
	pools map[string]*redis.Pool
}

func (rm *redisMap) init() {
	rm.pools = map[string]*redis.Pool{}
	rm.RegisterRedis(constant.LOGIN_REDIS,
		mt.Table.LoginRedis.GetById(0).GetHost(),
		mt.Table.LoginRedis.GetById(0).GetPort(),
		mt.Table.LoginRedis.GetById(0).GetPasswd(),
		mt.Table.LoginRedis.GetById(0).GetDatabase(),
		mt.Table.LoginRedis.GetById(0).GetMaxOpenConns(),
		mt.Table.LoginRedis.GetById(0).GetMaxIdleConns())
}

func (rm *redisMap) unInit() {

}

func (rm *redisMap) RegisterRedis(
	name string,
	host string,
	port int32,
	passwd string,
	dataBase int32,
	maxOpenConns int32,
	maxIdleConns int32) {
	pool := &redis.Pool{
		MaxIdle:   int(maxIdleConns),
		MaxActive: int(maxOpenConns),
		Dial: func() (redis.Conn, error) {
			address := host + ":" + q5.SafeToString(port)
			rc, err := redis.Dial(
				"tcp",
				address,
				redis.DialPassword(passwd),
				redis.DialDatabase(int(dataBase)))
			if err != nil {
				return nil, err
			}
			return rc, nil
		},
		IdleTimeout: time.Second,
		Wait:        true,
	}

	rm.pools[name] = pool
}

func (rm *redisMap) getConn(name string) redis.Conn {
	pool, ret := rm.pools[name]
	if !ret {
		return nil
	}

	return (*pool).Get()
}

func (rm *redisMap) Get(name string, key string) (value string, err error) {
	con := rm.getConn(name)
	if con == nil {
		return "", errors.New("")
	}
	defer con.Close()

	return redis.String(con.Do("get", key))
}
