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(s []string) {
	var isCfg []bool
	var dirs []string

	// 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
}



// 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
}
