package main_test

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"os"
	"pgm/config"
	"pgm/data"
	"pgm/loader"
	"pgm/logger"
	"testing"
)

// init should always return true
// init will not write incorrect values to file
func TestInit(t *testing.T) {
	t.Parallel()
	var cfg string
	testCases := []initTest{
		{a: "junk", b: "notreal", c: "failingonpurpose", want: true},
		{a: "test_host_dir", b: "test_screen_dr", c: "test_log_dir", want: true},
	}
	cfg, err := os.UserHomeDir()
	if err != nil {
		logger.Logger("failed to find home dir " + err.Error())
		fmt.Println("an error was encountered and logged")
		os.Exit(0)
	}
	for _, tc := range testCases {
		got := config.IsInit(tc.a, tc.b, tc.c, cfg + "/.pgm.yml")
		if tc.want != got {
			t.Errorf("want %t, got %t", tc.want, got)
		}
	}
}

func TestLogs(t *testing.T) {
	t.Parallel()
	var s string
	var want bool = true
	s = "test"
	got := logger.Logger(s)
	if want != got {
		t.Errorf("want %t, got %t", want, got)
	}
}

func TestLoadConfig(t *testing.T) {
	t.Parallel()
	var v *viper.Viper

	var want error = nil
	v, got := config.ReadConfig()
	_ = v
	if want != got {
		t.Error("load config reaturned a non nil error")
	}

}


// loader function will test that it can load the ui to chose a database
// and quits the ui.
// "test" is added into the array of files a user has configured and selected
func TestLoader(t *testing.T) {
	t.Parallel()
	var tc []string
	var s string
	var b string
	var want error = nil
	s = "test"
	b = "test"
	tc = data.ReadHosts()
	tc = append(tc, "test")
	got := loader.Loader(tc, s, b)
	if want != got {
		t.Errorf("want %t, got %t", want, got)
	}

}


func TestScreener(t *testing.T){
	t.Parallel()
	var p data.HostDetails
	var testDb string
	var want error = nil
	var h string
	h, err := os.UserHomeDir()
	if err != nil {
		logger.Logger("[ERROR] could not set home directory: " + err.Error())
		os.Exit(0)
	}
	viper.SetConfigName(".pgm") // config file name without extension
	viper.SetConfigType("yaml")
	viper.AddConfigPath(h)
	viper.AutomaticEnv() // read value ENV variable

	err = viper.ReadInConfig()
	if err != nil {
		logger.Logger("[ERROR] fatal error config file: " +  err.Error())
		os.Exit(1)
	}
	testDb = viper.GetString("test_db")
	err = json.Unmarshal([]byte(testDb), &p)
	if err != nil {
		logger.Logger("[LOG] test screener failed: " + err.Error())
		os.Exit(1)
	}
	got := loader.Screener(p)
	if want != got {
		t.Errorf("want %t, got %t", want, got)
	}



}

type viperHostTest struct {
	a string
	want bool
}


type initTest struct {
	a, b, c string
	want bool
}