package config

import (
	"gopkg.in/yaml.v2"
	"log"
	"os"
	"runtime"
)

var ostype = runtime.GOOS

var conf ConfAPI

type ConfAPI struct {
	ListenSvr  int         `yaml:"listen_svr"` // 服务监听端口
	ListenApi  int         `yaml:"listen_api"` // 服务监听端口
	RunMode    string      `yaml:"runmode"`    // 服务运行模式
	MaxConn    int         `yaml:"max_conn"`
	Logs       LogConfig   `yaml:"logs"` // 日志
	Redis1     EntityRedis `yaml:"redis1"`
	Mysql      MysqlConfig `yaml:"mysql"` // 认证配置
	Mysql1     MysqlConfig `yaml:"mysql1"` // 认证配置
	MongoConf  MongoConfig `yaml:"mongo"`
	CaCert    	string  		`yaml:"ca_cert"`
	ClientCert 	string 			`yaml:"client_cert"`
	ClientKey  	string  		`yaml:"client_key"'`
	init      	bool
}

type EntityRedis struct {
	Addr     string `yaml:"addr"`
	Pwd      string `yaml:"password"`
	DB       int    `yaml:"db"`
	PoolSize int    `yaml:"poolsize"`
}
type RedisConfig struct {
	Addr string `yaml:"addr"`
	Pwd  string `yaml:"password"`
	DB   int64  `yaml:"db"`
}
type LogConfig struct {
	Dir      string `yaml:"dir"`
	File     string `yaml:"file"`
	Level    int    `yaml:"level"`
	SaveFile bool   `yaml:"savefile"`
}
type MysqlConfig struct {
	Addr     string `yaml:"addr"`
	UserName string `yaml:"user"`
	Password string `yaml:"password"`
	Db       string `yaml:"db"`
	MaxOpen  int    `yaml:"max_open"`
	MaxIdle  int    `yaml:"max_idle"`
}
// mongodb://myuser:mypass@localhost:40001
type MongoConfig struct {
	Addr     string `yaml:"addr"`
	Port     int64  `yaml:"port"`
	UserName string `yaml:"user"`
	Password string `yaml:"password"`
	Db       string `yaml:"db"`
	MaxOpen  int    `yaml:"max_open"`
	MaxIdle  int    `yaml:"max_idle"`
}

var gConf ConfAPI

func Init(path string) error {
	file, e := os.Open(path)
	if nil != e {
		log.Println(e.Error())
		return e
	}
	stat, _ := file.Stat()
	filec := make([]byte, stat.Size())
	file.Read(filec)
	e = yaml.Unmarshal(filec, &gConf)
	if nil != e {
		log.Println(e.Error())
	}
	gConf.init = true
	return nil
}

func GetPort() int {
	if gConf.init {
		return gConf.ListenApi
	} else {
		return 8001
	}
}
func GetMysqlConfig() *MysqlConfig {
	if gConf.init {
		return &gConf.Mysql
	} else {
		return nil
	}
}
func GetMysqlBlogConfig() *MysqlConfig {
	if gConf.init {
		return &gConf.Mysql1
	} else {
		return nil
	}
}
func GETCaCert()  string{
	return gConf.CaCert
}
func GetMongoDBConfig()  *MongoConfig{
	if gConf.init{
		return  &gConf.MongoConf
	}	else {
		return nil
	}
}
func GetRedis1() *EntityRedis {
	if gConf.init {
		return &gConf.Redis1
	} else {
		return nil
	}
}
func GetLogConfig() *LogConfig {
	if gConf.init {
		return &gConf.Logs
	} else {
		return nil
	}
}

