package main

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

	"ems.agt/lib/log"
	"gopkg.in/yaml.v3"
)

// Yaml struct of config
type YamlConfig struct {
	Logger struct {
		File     string `yaml:"file"`
		Level    string `yaml:"level"`
		Duration int    `yaml:"duration"`
	}

	Rest struct {
		BindIP string `yaml:"bindip"`
		Port   uint16 `yaml:"port"`
	}
}

var yamlConfig YamlConfig

func ReadConfig(configFile string) {
	yamlFile, err := ioutil.ReadFile(configFile)
	if err != nil {
		fmt.Printf("ioutil.ReadFile %s err %v", configFile, err)
	}
	//	fmt.Println("yamlfile:", string(yamlFile))

	err = yaml.Unmarshal(yamlFile, &yamlConfig)
	if err != nil {
		fmt.Printf("Unmarshal: %v when to struct", err)
	}
}

func GetYamlConfig() *YamlConfig {
	return &yamlConfig
}

func GetLogLevel() log.LogLevel {
	var logLevel log.LogLevel
	switch strings.ToLower(yamlConfig.Logger.Level) {
	case "trace":
		logLevel = log.LOG_TRACE
	case "info":
		logLevel = log.LOG_INFO
	case "debug":
		logLevel = log.LOG_DEBUG
	case "warn":
		logLevel = log.LOG_WARN
	case "error":
		logLevel = log.LOG_ERROR
	case "fatal":
		logLevel = log.LOG_FATAL
	case "off":
		logLevel = log.LOG_OFF
	default:
		logLevel = log.LOG_DEBUG
	}
	return logLevel
}

const defaultConfigFile = "./tt.yaml"

var (
	version   string
	buildTime string
	goVer     string
)

func init() {
	cfile := flag.String("c", defaultConfigFile, "config file")
	pv := flag.Bool("v", false, "print version")
	ph := flag.Bool("h", false, "print help")

	flag.Parse()
	if *pv {
		fmt.Printf("OMC version: %s\n%s\n%s\n\n", version, buildTime, goVer)
		os.Exit(0)
	}
	if *ph {
		flag.Usage()
		os.Exit(0)
	}

	ReadConfig(*cfile)
}
