package main

import (
	"flag"
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

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

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

	Database struct {
		Type     string `yaml:"type"`
		User     string `yaml:"user"`
		Password string `yaml:"password"`
		Host     string `yaml:"host"`
		Port     string `yaml:"port"`
		Name     string `yaml:"name"`
	} `yaml:"database"`

	Mml struct {
		FileDir string `yaml:"filedir"`
		Table   string `yaml:"table"`
	} `yaml:"mml"`
}

var yamlConfig YamlConfig

func ReadConfig(configFile string) {
	yamlFile, err := os.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
}

var mapYaml map[string]interface{}

func ReadMMLConfig(fileName string) *map[string]interface{} {
	file, err := os.ReadFile(fileName)
	if err != nil {
		fmt.Println("yamlFile.Get err", err)
	}

	mapYaml = make(map[string]interface{})

	err = yaml.Unmarshal(file, &mapYaml)
	if err != nil {
		fmt.Printf("yaml.Unmarshal: %v when to struct\n", err)
	}
	//	fmt.Println("mapYaml:", mapYaml)

	return &mapYaml
}

func GetAllFile(dir string, s []string) ([]string, error) {
	fmt.Println("GetAllFile processing...", dir)
	fmt.Println("dir:", dir)

	rd, err := os.ReadDir(dir)
	if err != nil {
		fmt.Println("read dir fail:", err)
		return s, err
	}

	for _, fi := range rd {
		if !fi.IsDir() {
			fullName := dir + "/" + fi.Name()
			s = append(s, fullName)
		}
	}
	return s, nil
}

const defaultConfigFile = "./loadmconf.yaml"

var (
	version   string
	buildTime string
	goVer     string
)

var pfiles []string

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

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

	ReadConfig(*cfile)

	fmt.Println("pfile:", *pfile)
	if *pfile != "" {
		pfiles = append(pfiles, *pfile)
	} else {
		pfiles, _ = GetAllFile(yamlConfig.Mml.FileDir, pfiles)
	}
	fmt.Println("pfiles:", pfiles)
}
