package config

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"github.com/spf13/viper"
)

// 数据库配置项
var cfgDatabase *viper.Viper

// 应用配置项
var cfgApplication *viper.Viper

// Token配置项
var cfgJwt *viper.Viper

// Log配置项
var cfgLogger *viper.Viper

// Ssl配置项 非必须
var cfgSsl *viper.Viper

// 代码生成配置项 非必须
var cfgGen *viper.Viper

// 导出文件配置项 非必须
var cfgExport *viper.Viper

var cfgMessage *viper.Viper

// Setup 载入配置文件
func Setup(path string) {
	viper.SetConfigFile(path)
	content, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatal(fmt.Sprintf("Read config file fail: %s", err.Error()))
	}

	//Replace environment variables
	err = viper.ReadConfig(strings.NewReader(os.ExpandEnv(string(content))))
	if err != nil {
		log.Fatal(fmt.Sprintf("Parse config file fail: %s", err.Error()))
	}

	cfgDatabase = viper.Sub("settings.database")
	if cfgDatabase == nil {
		panic("No found settings.database in the configuration")
	}
	DatabaseConfig = InitDatabase(cfgDatabase)

	cfgApplication = viper.Sub("settings.application")
	if cfgApplication == nil {
		panic("No found settings.application in the configuration")
	}
	ApplicationConfig = InitApplication(cfgApplication)

	cfgJwt = viper.Sub("settings.jwt")
	if cfgJwt == nil {
		panic("No found settings.jwt in the configuration")
	}
	JwtConfig = InitJwt(cfgJwt)

	cfgLogger = viper.Sub("settings.logger")
	if cfgLogger == nil {
		panic("No found settings.logger in the configuration")
	}
	LoggerConfig = InitLog(cfgLogger)

	cfgSsl = viper.Sub("settings.ssl")
	if cfgSsl == nil {
		// Ssl不是系统强制要求的配置，默认可以不用配置，将设置为关闭状态
		fmt.Println("warning config not found settings.ssl in the configuration")
		SslConfig = new(Ssl)
		SslConfig.Enable = false
	} else {
		SslConfig = InitSsl(cfgSsl)
	}

	cfgGen = viper.Sub("settings.gen")
	if cfgGen == nil {
		panic("No found settings.gen")
	}
	GenConfig = InitGen(cfgGen)

	cfgExport = viper.Sub("settings.export")
	if cfgExport == nil {
		panic("No found settings.export")
	}
	ExportConfig = InitExport(cfgExport)

	cfgMessage = viper.Sub("settings.message")
	if cfgMessage == nil {
		panic("No found settings.message")
	}
	MessageConfig = InitMessage(cfgMessage)
}
