/*
Copyright © 2020 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"encoding/json"
	"fmt"
	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"io/ioutil"
	"log"
	"shiny-pancake/internal/model"

	"os"
	"shiny-pancake/logger"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
	Use:   "add",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
	loadForm()
	},
}

func init() {
	rootCmd.AddCommand(addCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// addCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}


func loadForm()  {
	app := tview.NewApplication()
	form := tview.NewForm().
		AddInputField("hostname", "", 63, nil, nil).
		AddInputField("databaseName", "", 63, nil, nil).
		AddInputField("username", "", 63, nil, nil).
		AddPasswordField("password", "", 63, '*', nil).
		AddButton("Save", func() {
			app.Stop()
		}).
		AddButton("Quit", func() {
			app.Stop()
		})
	form.SetBorder(true).SetTitle("define database").SetTitleAlign(tview.AlignLeft).SetBackgroundColor(tcell.ColorGrey).SetTitleColor(tcell.ColorYellow)
	if err := app.SetRoot(form, true).EnableMouse(true).Run(); err != nil {
		panic(err)
	}
	configWriter(form)

}



//// Writes configs to correct directory based on the config file
func configWriter(f *tview.Form){
	var ip []string
	var fp string
	var hostFile string
	var cfg []byte
	var c model.HostDetails
	var hd string
	hd = viper.GetString("hostsDirectory")

	for a := 0; a < 4; a++ {
		var inputValue string
		inputField := f.GetFormItem(a).(*tview.InputField)
		inputValue = inputField.GetText()
		if len(inputValue) <1 {
			var l logger.Log
			l = logger.Log{"warn", logrus.Fields{"add config": "empty form"}, "zero length input value not allowed"}
			logger.Lgr(&l)
			fmt.Println("blank value provided. unable to save config, please retry.")
			os.Exit(0)
		}
		ip = append(ip, inputValue)

		}
		hostFile = ip[0]
		if _, err := os.Stat(hd + "/" + hostFile ); os.IsNotExist(err) {
			fp = hd + "/" + hostFile
		} else {
			var l logger.Log
			l = logger.Log{"warn", logrus.Fields{"duplicate file": hostFile}, "duplicate configuration file names not allowed"}
			logger.Lgr(&l)
			fmt.Println("duplicate hostname used. unable to save config, please retry.")
			os.Exit(1)
		}

		file, err := os.Create(fp)
		c = model.HostDetails{ip[3], hostFile, ip[1], ip[2]}
		if err != nil {
			log.Fatal("unable to create file: " + fp)
		}
		defer file.Close()
		if err != nil {
			log.Fatal("error writing to file: " + err.Error())
		}
		cfg, err = json.MarshalIndent(c, "", " ")
		if err != nil {
			log.Fatal(err)
		}
		var l logger.Log
		err = ioutil.WriteFile(fp, cfg, 0644)
		if err !=nil{
			log.Fatal(err)
		}
		l = logger.Log{"info", logrus.Fields{"file": hostFile}, "created"}
		logger.Lgr(&l)
	}


