package config

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
	"os"
	"pgm/logger"
	"strings"
)

// checks to make sure things look like we want locally.
func IsInit(h string, s string, l string, cfgFile string) bool {
	var isCfg []bool
	var dirs []string
	dirs = cfgExists(h, dirs, cfgFile)
	dirs = cfgExists(s, dirs, cfgFile)
	dirs = cfgExists(l, dirs, cfgFile)
	homeDirectory, err := os.UserHomeDir()
	if err != nil {
		log.Fatal(err)
	}
	// if there is no $HOME/.pgm dir
	if _, err := os.Stat(homeDirectory + "/.pgm"); os.IsNotExist(err) {
		err = os.Mkdir(homeDirectory+"/.pgm/", 0755)
		if err != nil {
			log.Fatal(err)
		}
	}
	// creates logs, src, and hosts directories.
	for _, f := range dirs {
		if len(f) > 0 {
			err := os.MkdirAll(homeDirectory+"/"+f, 0755)
			if err != nil {
				log.Fatal(err)
			}
			isCfg = append(isCfg, true)
		}
	}

	for _, b := range isCfg {
		if b == false {
			return false
		}
	}
	return true
}

// determines if key exists in config file
func cfgExists(s string, d []string, cfgFile string) []string {
	var dir []string
	var cfgPath string
	dir = strings.Split(s, "/")
	cfgPath = dir[len(dir)-1]

	configDirectoryKey := parseCfg(cfgPath)
	if err := viper.ReadInConfig(); err == nil {
		viper.SetConfigFile(cfgFile)
	}
	if viper.GetString(configDirectoryKey) != "" {
		a := viper.GetString(configDirectoryKey)
		d = append(d, a)
	} else {
		d = append(d, "")
	}
	return d
}

// neatly return a string formatted to match the config file
func parseCfg(s string) string {
	var directory string
	var isTest string
	// if we have test directories these are configured already in .pgm.yaml
	isTest = s[:3]
	if isTest == "test" {
		return s
	}
	directory = "%s_dir"
	directory = fmt.Sprintf(directory, s)
	return directory

}

// repeated method to get config data
func ReadConfig() (*viper.Viper, error) {
	var filename string
	var h string
	h, err := os.UserHomeDir()
	if err != nil {
		lgd := logger.Logger("failed to open config " + err.Error())
		if lgd == true {
			fmt.Println("failed to read config, failure was logged")
		}

	}
	filename = h + "/" + ".pgm.yaml"
	v := viper.New()

	v.AutomaticEnv()
	if err := v.ReadInConfig(); err == nil {
		v.SetConfigFile(filename)
		return v, err
	}
	return v, nil
}
