package configs

import (
	"crm-api/pkg/lfshook"
	"io/ioutil"
	"os"

	"github.com/gofrs/uuid"
	log "github.com/sirupsen/logrus"

	"gopkg.in/yaml.v2"
)

// Config https://godoc.org/gopkg.in/yaml.v2
// Config 存储配置
type Config struct {
	IdentityKey string `yaml:"identityKey"`
	PbxNumber   string `yaml:"pbxnumber"`

	AsteriskAMIHost   string `yaml:"asteriskAMIHost"`   // Host
	AsteriskAMIPort   string `yaml:"asteriskAMIPort"`   // Port
	AsteriskAMIUser   string `yaml:"asteriskAMIUser"`   // User
	AsteriskAMISecret string `yaml:"asteriskAMISecret"` // Secret

	MysqlDBHost   string `yaml:"mysqlDBHost"`   // Host
	MysqlDBUser   string `yaml:"mysqlDBUser"`   // User
	MysqlDBSecret string `yaml:"mysqlDBSecret"` // Secret
	MysqlDBName   string `yaml:"mysqlDBName"`   // Name

	RedisDBHost   string `yaml:"redisDBHost"`   // Host
	RedisDBPort   string `yaml:"redisDBPort"`   // User
	RedisDBSecret string `yaml:"redisDBSecret"` // Secret

	LogInfoPath  string `yaml:"logInfoPath"`  //logInfoPath
	LogErrorPath string `yaml:"logErrorPath"` //logErrorPath

	StoragePath string `yaml:"storagePath"` // 存储目录
	LogoPath    string `yaml:"logoPath"`    // 存储目录

	WebType string `yaml:"webtype"` //https http
	WebHost string `yaml:"webhost"` //Host
	WebPort int    `yaml:"webport"` //port

	AllowOrigin string `yaml:"allowOrigin"` // allowOrigin

	PushConfig string `yaml:"pushConfig"` // 推送配置目录
	I18nPath   string `yaml:"i18nPath"`   //i18n

	LogLevel log.Level //logLevel

	// BasicAuthUser string `yaml:"basicAuthUser"` //BasicAuth Username
	// BasicAuthPWD  string `yaml:"basicAuthPWD"`  //BasicAuth Password
	// ApiKey        string `yaml:"apiKey"`        //ApiKey
	// ApiKeyValue   string `yaml:"apiKeyValue"`   //ApiKeyValue

}

// ConfigPath 配置文件路径
var ConfigPath = "./config.yaml"

// ConfigGlobal 全局配置变量
var ConfigGlobal *Config

// DecodeConfig 解析配置
func DecodeConfig() {
	_, err := os.Stat(ConfigPath)
	if err != nil {
		lfshook.NewLogger().Errorf("config file not exist %+v", err)
		return
	}

	fileByte, err := ioutil.ReadFile(ConfigPath)
	if err != nil {
		lfshook.NewLogger().Errorf("read config file %+v", err)
		return
	}

	ConfigGlobal = &Config{}
	err = yaml.Unmarshal(fileByte, ConfigGlobal)
	if err != nil {
		lfshook.NewLogger().Errorf("Unmarshal config file %+v", err)
		return
	}

	// jwt secret 生成
	if ConfigGlobal.IdentityKey == "" {
		uuid, _ := uuid.NewV4()
		ConfigGlobal.IdentityKey = uuid.String()
		EncodeConfig()
	}
}

// EncodeConfig 保存配置
func EncodeConfig() error {
	out, _ := yaml.Marshal(ConfigGlobal)
	err := ioutil.WriteFile(ConfigPath, out, 0777)
	if err != nil {
		lfshook.NewLogger().Errorf("save config file %+v", err)
	}
	return err
}
