package comm

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/go-redis/redis/v8"
)

func createRedisClient(rediscnf string) (*redis.Client, error) {
	redisOps := strings.Split(rediscnf, "#")
	if len(redisOps) < 2 {
		return nil, fmt.Errorf("无效redis地址 需要127.0.0.1:16379#0#username#password当前 %s", rediscnf)
	}

	fmt.Println("redis-format addr => ", redisOps[0])

	db, err := strconv.Atoi(redisOps[1])
	if err != nil {
		return nil, errors.New("非法redis数据库 id")
	}

	connOption := &redis.Options{
		Addr: redisOps[0],
		DB:   db, // use default DB
	}

	if len(redisOps) == 4 {
		connOption.Username = redisOps[2]
		connOption.Password = redisOps[3]
	}
	return redis.NewClient(connOption), err
}

func (bus *NatsBus) NewRedisFromConfig(redisConfKey string, timeout ...interface{}) (*redis.Client, error) {
	//127.0.0.1:16379#0#username#password
	rediscnf, err := bus.RequestConfig(redisConfKey)
	if err != nil {
		panic(err)
	}

	redisenv := os.Getenv("REDIS")
	if len(redisenv) > 0 {
		rediscnf = redisenv
	}
	fmt.Println("config rediscnf => ", rediscnf)
	fmt.Println("env rediscnf => ", redisenv)

	return createRedisClient(rediscnf)
}

func (bus *NatsBus) NewRedisFromConfigDev(redisConfKey string, timeout ...interface{}) (*redis.Client, error) {
	//127.0.0.1:16379#0#username#password
	rediscnf, err := bus.RequestConfigDev(redisConfKey)
	if err != nil {
		panic(err)
	}
	redisenv := os.Getenv("REDIS")
	if len(redisenv) > 0 {
		rediscnf = redisenv
	}
	fmt.Println("config rediscnf => ", rediscnf)
	fmt.Println("env rediscnf => ", redisenv)
	return createRedisClient(rediscnf)
}
