package config

import (
	"errors"
	"io/ioutil"
	"os"
	"path"

	"git.trj.tw/golang/utils"
	yaml "gopkg.in/yaml.v2"
)

// Config -
type Config struct {
	Port     int `yaml:"port"`
	Database struct {
		Host string `yaml:"host"`
		Port int    `yaml:"port"`
		User string `yaml:"user"`
		Pass string `yaml:"pass"`
		DB   string `yaml:"db"`
	} `yaml:"database"`
	Line struct {
		Access string `yaml:"access"`
		Secret string `yaml:"secret"`
	} `yaml:"line"`
	Redis struct {
		Host   string `yaml:"host"`
		Port   int    `yaml:"port"`
		Prefix string `yaml:"prefix"`
	}
}

var conf *Config

// LoadConfig -
func LoadConfig(p ...string) error {
	var fp string

	if len(p) > 0 && len(p[0]) > 0 {
		fp = p[0]
	} else {
		wd, err := os.Getwd()
		if err != nil {
			return err
		}
		fp = path.Join(wd, "config.yml")
	}

	exists := utils.CheckExists(fp, false)
	if !exists {
		return errors.New("config file not exists")
	}

	data, err := ioutil.ReadFile(fp)
	if err != nil {
		return err
	}

	conf = &Config{}
	err = yaml.Unmarshal(data, conf)
	if err != nil {
		return err
	}

	return nil
}

// GetConf -
func GetConf() *Config {
	return conf
}
