package conf

import (
	"fmt"
	"os"
	"updater/log"

	"github.com/spf13/viper"
)

type ProxyItem struct {
	BusName string
	Nats    string
	DevNats string
	Apis    []string
	Streams []string
}

type ConfigerItem struct {
	Name     string
	Value    string
	DevValue string
}

type Log struct {
	FileName    string
	Level       int32
	ServiceName string
}

type Nats struct {
	Url               string
	MaxReconnect      int
	ReconnDelaySecond int
}

type AppConf struct {
	Configer []*ConfigerItem
	Adapter  []*ProxyItem
	Log
	Nats

	StartLocalNats bool //是否启动本地nats

	NatsExe string
	NatsDir string

	DataDir     string
	ExeDir      string
	NatsApiPort int
	NatsWsPort  int
	AppDataPort int
	Ip          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)

	nats := os.Getenv("NATS")
	if len(nats) > 0 {
		c.Nats.Url = nats
	}
	fmt.Println("app.yaml Env NATS=>", c.Nats.Url)
	return c, nil
}

var AppConfig *AppConf = nil
