package config

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
	"os"
	"strconv"
)

var (
	LogRedis   *redis.Client
	GameRedis  *redis.Client
	RedisGroup map[int]*redis.Client
)

func InitRedis() {
	LogRedis = newRedis(os.Getenv("LOG_REDIS_ADDR"), os.Getenv("LOG_REDIS_PW"), os.Getenv("LOG_REDIS_DB"))

	RedisGroup = make(map[int]*redis.Client)
	GameRedis = newRedis(os.Getenv("REDIS_ADDR"), os.Getenv("REDIS_PW"), os.Getenv("REDIS_DB"))
	RedisGroup[1] = GameRedis

	failNum := 0
	for i := 2; i < 10000; i += 1 {
		addrKey := fmt.Sprintf("REDIS%v_ADDR", i)
		pwKey := fmt.Sprintf("REDIS%v_PW", i)
		dbKey := fmt.Sprintf("REDIS%v_DB", i)

		addr := os.Getenv(addrKey)
		if addr == "" {
			failNum += 1
			if failNum > 3 {
				return
			}
			continue
		}

		logrus.Printf("InitRedis %v", addrKey)

		RedisGroup[i] = newRedis(os.Getenv(addrKey), os.Getenv(pwKey), os.Getenv(dbKey))
	}

}

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
}

// PubMessage 发布
func PubMessage(channel, msg string) {
	LogRedis.Publish(channel, msg)
}

// SubMessage 订阅
func SubMessage(channel string, call func(msg *redis.Message)) {
	sub := LogRedis.Subscribe(channel)
	_, err := sub.Receive()
	if err != nil {
		panic(err)
	}

	for msg := range sub.Channel() {
		call(msg)
	}
}
