package conf

import (
	"fmt"
	"os"

	"mesh/log"

	"github.com/spf13/viper"
)

const (
	SaveType_Obs   = "obs"
	SaveType_OSS   = "oss"
	SaveType_Minio = "minio"
)

type DefaultCategoryConf struct {
	Children []*DefaultCategoryConf
	Name     string //分类名字
	Value    string //分类的值
}

type AppConf struct {
	Name     string
	Version  string
	SaveType string //obs, oss, minio

	Jwt struct {
		Realm       string
		Key         string
		TimeoutHour int
	}

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

	Debug struct {
		UserId    string
		UserPhone string
		UserRole  string
	}

	Obs struct {
		Bucket      string
		AccessKeyId string
		SecrateKey  string
		Endpoint    string
	}

	Minio struct {
		Bucket   string
		PubHost  string
		Endpoint string

		AccessKey string
		AccessSec string
	}
	Nats struct {
		Url               string
		MaxReconnect      int
		ReconnDelaySecond int
	}
}

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
