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
}

// returns a value from the .pgm.yaml file
func ViperReturnKey(k string ) 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("scr")
	viper.SetConfigType("json")

	viper.AddConfigPath(h + "/.pgm/scn/")
	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)
	}
	s = viper.GetString(k)
	logger.Logger("[LOG] got value from .pgm.yaml: " + s )
	return s
}
