/*
Copyright © Brian Buller <brian@bullercodeworks.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd

import (
	"fmt"
	"os"

	"git.bullercodeworks.com/brian/expds/data"
	"git.bullercodeworks.com/brian/expds/helpers"
	gap "github.com/muesli/go-app-paths"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// rootCmd represents the base command when called without any subcommands
var (
	Version   = "1.0"
	Build     = 1
	Name      = "expds"
	cfgFile   string
	ConfigDir = ""
	rootCmd   = &cobra.Command{
		Use:   "expds",
		Short: "Utility to edit and view PDS",
		RunE:  runUI,
	}
)

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")
}

func initConfig() {
	viper.SetEnvPrefix(data.EnvPrefix)
	var firstDir string
	if cfgFile == "" {
		scope := gap.NewScope(gap.User, Name)
		dirs, err := scope.ConfigDirs()
		if err != nil {
			fmt.Println("Can't retrieve default config")
			os.Exit(1)
		}
		firstDir = dirs[0]
		for _, v := range dirs {
			viper.AddConfigPath(v)
		}
		viper.SetConfigName(Name)
		viper.SetConfigType("yaml")
	}

	viper.SetDefault(data.KeyConfigDir, firstDir)
	viper.SetDefault(data.KeyDebug, false)
	viper.SetDefault(data.KeyDataDir, helpers.Path(firstDir, "data"))
	viper.SetDefault(data.KeyVimMode, false)
	viper.SetConfigFile(cfgFile)
	viper.AutomaticEnv()

	configName := fmt.Sprintf("%s.yaml", Name)
	var createConfig bool
	ConfigDir = fmt.Sprintf("%s%s", firstDir, helpers.Sep)
	configPath := helpers.Path(ConfigDir, configName)
	if err := viper.ReadInConfig(); err != nil {
		createConfig = true
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			fmt.Println("Config file not found.")
		} else {
			fmt.Println("Config file found, but some other error occurred.")
			fmt.Println(err)
		}
	}
	if createConfig {
		_, err := os.Stat(firstDir)
		if os.IsNotExist(err) {
			fmt.Println("Creating Directory:", firstDir)
			err := os.Mkdir(firstDir, 0o755)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
		fmt.Println("Writing Config as:", configPath)
		if err = viper.WriteConfigAs(configPath); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}

	dDir := viper.GetString(data.KeyDataDir)
	_, err := os.Stat(dDir)
	if os.IsNotExist(err) {
		fmt.Println("Creating Data Directory:", dDir)
		err := os.Mkdir(dDir, 0o755)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
}
