package data

import (
	"flag"
	"git.quantgroup.cn/DevOps/enoch/service/conf"
	"github.com/gomodule/redigo/redis"
	"time"
)

func newPool(server, password string) *redis.Pool {
	var redisConf = conf.GlobalConfig.Redis
	return &redis.Pool{
		MaxIdle:     redisConf.MaxIdle,
		MaxActive:   redisConf.MaxActive,
		IdleTimeout: redisConf.IdleTimeout * time.Second,
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if password != "" {
				if _, err := conn.Do("AUTH", password); err != nil {
					conn.Close()
					return nil, err
				}
			}
			return conn, err
		},
		TestOnBorrow: func(conn redis.Conn, t time.Time) error {
			_, err := conn.Do("PING")
			return err
		},
		Wait: true,
	}
}

var (
	Pool          *redis.Pool
	redisServer   = flag.String("redisServer", conf.GlobalConfig.Redis.Host+":"+conf.GlobalConfig.Redis.Port, "")
	redisPassword = flag.String("redisPassword", "", "")
)

func RedisPoolInit() {
	flag.Parse()
	Pool = newPool(*redisServer, *redisPassword)
}
