package data

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

// Simple config file for connecting to databases.
type HostDetails struct {
	Secret       string `json:"secret"`
	Hostname     string `json:"hostname"`
	DatabaseName string `json:"databaseName"`
	Username     string `json:"username"`
}

func ReadHosts() []string {
	var pgee []string
	var homeDir string
	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Fatal(err)
	}

	file, err := os.Open(homeDir + "/.pgm/hosts")
	if err != nil {
		logged := logger.Logger("failed opening directory: %s" + err.Error())
		if logged == true {
			fmt.Println("failed to load hosts, failure was logged")
		}

	}
	defer file.Close()

	pgee, err = file.Readdirnames(0) // 0 to read all files and folders
	if err != nil {
		log.Fatal(err)
	}
	return pgee
}

// handles interacting with the config file.
func ViperPgmConfig(k string, a string) (bool, string) {
	var h string
	var s string
	h, err := os.UserHomeDir()
	if err != nil {
		logger.Logger("[ERROR] could not set home directory: " + err.Error())
		os.Exit(0)
	}
	viper.SetConfigName(".pgm")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(h)
	err = viper.ReadInConfig() // Find and read the config file
	if err != nil {            // Handle errors reading the config file
		logger.Logger("[ERROR] failed to load viper config: " + err.Error())
		fmt.Println("error occurred and was logged.")
		os.Exit(1)
	}
	// r returns values, may add an action to update or set values later if it makes sense
	switch a {
	case "r":
		if viper.IsSet(k) {
			s = viper.GetString(k)
			logger.Logger("[LOG] got value from .pgm.yaml: key = " + k + ", value = " + s)
			return true, s
		}
		return false, ""
	default:
		logger.Logger("[LOG] invalid action passed to Viper return key. use \"r\" for return")
		return false, ""
	}
	return false, ""
}

func ViperScrConfig(filename string, defaults map[string]interface{}) (*viper.Viper, error){
	v := viper.New()
	for key, value := range defaults {
		v.SetDefault(key, value)
	}
	v.SetConfigName(filename)
	v.AddConfigPath( "/home/jms/.pgm/scn")
	v.AutomaticEnv()
	err := v.ReadInConfig()
	return v, err
}

type ViewCfg struct {
	q         string `mapstructure:"query"`
	c         int    `mapstructure:"column"`
	datatypes string `mapstructure:"datatypes"`
	uiT       bool   `mapstructure:"uiType"`
	t         string `mapstructure:"title"`
}
