package configs

import (
	"io/ioutil"
	"os"
	"pbx-api-gin/pkg/lfshook"

	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"`

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

	//AsteriskAGIPort string `yaml:"asteriskAGIPort"` // AGIPort

	//AsteriskTriggerPath      string `yaml:"asteriskTriggerPath"`      // 广播触发规则
	//AsteriskPagingPath       string `yaml:"asteriskPagingPath"`       // 广播规则
	//AsteriskBroadcastTimeout int64  `yaml:"asteriskBroadcastTimeout"` // 广播响铃时长
	//AsteriskBroadcastName    string `yaml:"asteriskBroadcastName"`    // 广播时名称
	//AsteriskBroadcastID      string `yaml:"asteriskBroadcastID"`      // 广播时ID

	//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
	RecordEventLog string `yaml:"recordingEvent"` //recordingEventfile
	ProcessRecord  string `yaml:"processRecord"`  //processRecord

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

	//AllEventPushUrl string `yaml:"allEventPushUrl"`

	//WebHost string `yaml:"webhost"` //Host
	//WebPort int64  `yaml:"webport"` //port

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

	LogLevel log.Level //logLevel
}

// ConfigPath 配置文件路径
var ConfigPath = "/data/test/configs/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)
	}

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

// 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
}
