package commands

import (
	"github.com/kelseyhightower/envconfig"
	"gopkg.in/yaml.v3"
	"os"
	"os/user"
	"strings"
)

const configName = "config.yaml"

type Configuration struct {
	Document struct {
		Path     string `yaml:"Path" envconfig:"PATH"`
		Template string `yaml:"Template" envconfig:"TEMPLATE"`
	} `yaml:"Document"`
}

func checkAndInitConfiguration(name string) bool {

	if name == "" {
		return false
	}

	ptr, err := os.Open(name)
	if err != nil {
		return false
	}
	defer ptr.Close()

	decoder := yaml.NewDecoder(ptr)
	err = decoder.Decode(state.configuration)

	if err != nil {
		return false
	}

	return true
}

func initConfiguration() {

	userConfig := ""

	usr, err := user.Current()
	if err == nil {
		userConfig = usr.HomeDir + "/.config/" + state.info.Mnemonic + "/" + configName
	}

	current, err := os.Getwd()
	if err == nil {
		current = current + "/" + configName
	}

	state.configuration = &Configuration{}
	err = envconfig.Process(strings.ToUpper(state.info.Mnemonic), state.configuration)
	CheckError(err)

	for _, path := range []string{
		state.definition.ConfigurationPath,
		current,
		userConfig,
		"/etc/" + state.info.Mnemonic + "/" + configName} {
		if checkAndInitConfiguration(path) {
			return
		}
	}

}