package conf

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

	"copter-train/log"

	"github.com/spf13/viper"
)

type AppConf struct {
	Name    string
	Version string

	Jwt struct {
		Realm       string
		Key         string
		TimeoutHour int
	}

	Log struct {
		FileName    string
		Level       int32
		ServiceName string
	}
	Port  int32
	Mongo struct {
		DSN      string
		Database string
	}

	Configer struct {
		Mongo string
		Redis string
	}

	Nats struct {
		Url               string
		MaxReconnect      int
		ReconnDelaySecond int

		OsgconvStreamTopic string
		ShadowStreamTopic  string
		HdrProcStreamTopic string
		RenderStreamTopic  string
	}
}

func LoadConfFile(filepath string) (*AppConf, error) {
	file, err := os.Open(filepath)
	if err != nil {
		log.Errorf("can not open file:%s", filepath)
		return nil, err
	}
	v := viper.New()
	v.SetConfigType("yaml")
	err = v.ReadConfig(file)
	if err != nil {
		return nil, err
	}
	c := new(AppConf)
	err = v.Unmarshal(c)
	return c, err
}

func NewAppConf(filePath string) (*AppConf, error) {

	c, err := LoadConfFile(filePath)
	if err != nil {
		return c, err
	}

	//初始化log
	_ = log.NewLoggerSugar(c.Log.ServiceName, c.Log.FileName, c.Log.Level)

	mongo := os.Getenv("CONFIGER_MONGO")
	if len(mongo) > 0 {
		c.Configer.Mongo = mongo
	}
	fmt.Println("configer.Mongo=>", c.Configer.Mongo)

	//redis
	redis := os.Getenv("CONFIGER_REDIS")
	if len(redis) > 0 {
		c.Configer.Redis = redis
	}
	fmt.Println("configer.REDIS=>", c.Configer.Redis)

	// CONFIGER_JWT: spu3d#spu3d secret#24
	jwt := os.Getenv("CONFIGER_JWT")
	if len(jwt) > 0 {
		jwtConfig := strings.Split(jwt, "#")
		if len(jwtConfig) == 3 {
			c.Jwt.Realm = jwtConfig[0]
			c.Jwt.Key = jwtConfig[1]
			jwtTimeOut, _ := strconv.Atoi(jwtConfig[2])
			c.Jwt.TimeoutHour = jwtTimeOut
		}
	}
	fmt.Printf("conf.jwt=>Realm:%s,Key:%s,TimeoutHour:%d\n", c.Jwt.Realm, c.Jwt.Key, c.Jwt.TimeoutHour)
	fmt.Println("CONFIGER_JWT=>", jwt)

	//nats
	natsUrl := os.Getenv("NATS")
	if len(natsUrl) > 0 {
		c.Nats.Url = natsUrl
	}
	fmt.Println("NATS URL =>", c.Nats.Url)

	AppConfig = c

	return c, nil
}

var AppConfig *AppConf = nil
