package conf

import (
	"fmt"
	"os"

	"nrhe-train/log"

	"github.com/spf13/viper"
)

type AppConf struct {
	Name    string
	Version string

	Jwt struct {
		Realm       string
		Key         string
		TimeoutHour int
	}
	ServerPort int

	Redis struct {
		Addr     string
		Password string // no password set
		Db       int    // use default DB
	}
	Log struct {
		FileName    string
		Level       int32
		ServiceName string
	}
	Port  int32
	Mongo struct {
		DSN      string
		Database string
	}

	UploadPkgUrl string

	Nats struct {
		Url                      string
		MaxReconnect             int
		ReconnDelaySecond        int
		TileConvStreamTopic      string
		TileImageConvStreamTopic string

		MattingRequestStreamTopic string
		MattingResultStreamTopic  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)

	natsHost := os.Getenv("NATS")
	if len(natsHost) > 0 {
		c.Nats.Url = natsHost
	}
	fmt.Println("Env NATS=>", natsHost)

	AppConfig = c
	return c, nil
}

var AppConfig *AppConf = nil
