package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"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"`

	CmFileDir string `yaml:"cmfiledir"`
}

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 GetAllFile(dir string, s []string) ([]string, error) {
	fmt.Println("GetAllFile processing...", dir)
	fmt.Println("dir:", dir)

	rd, err := ioutil.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 = "./loadcmxls.yaml"

var (
	version   string
	buildTime string
	goVer     string
)

var pfiles []string

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

	flag.Parse()
	if *pv {
		fmt.Printf("OMC loadpmxls 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.CmFileDir, pfiles)
	}
	fmt.Println("pfiles:", pfiles)
}
