package conf

import (
	"fmt"
	"os"

	"box-cost/log"

	"github.com/spf13/viper"
)

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

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

	Jwt struct {
		Realm       string
		Key         string
		TimeoutHour 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
	}

	Debug struct {
		UserId    string
		UserPhone string
		UserRole  string
	}

	Nats struct {
		Url               string
		MaxReconnect      int
		ReconnDelaySecond int
	}

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

	Auth struct {
		Endpoint     string
		ClientId     string
		ClientSecret string

		Certificate      string
		OrganizationName string
		ApplicationName  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
	}
	pdfApiAddr := os.Getenv("TOPDF_ADDR")
	if len(pdfApiAddr) > 0 {
		c.PdfApiAddr = pdfApiAddr
	}
	fmt.Println("pdf_config=>", c.PdfApiAddr)
	fmt.Println("pdf_env=>", pdfApiAddr)
	AppConfig = c
	return c, nil
}

var AppConfig *AppConf = nil
