package cmd

import (
    "fmt"
    "github.com/mitchellh/go-homedir"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "os"
)

const (
    Key = ""
)

var rootCmd = &cobra.Command{
    Use:   "pastee",
    Short: "A quick and easy to use Command-Line Paste Interface",
    Long: `Fast, ad-free, secure, and feature filled! Submit pastes to Paste.ee from any operating system, anywhere!`,
    Args: cobra.ArbitraryArgs,
    Run: uploadCommandHandler,
}

var (
    cfgFile     string
)

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func init() {
    cobra.OnInitialize(initConfig)

    rootCmd.PersistentFlags().BoolP("encrypt", "e", true, "Encrypt uploaded contents")
    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
    rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
    viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
    viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
    viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
    viper.SetDefault("license", "apache")
    viper.SetDefault("apiKey", Key)

    rootCmd.AddCommand(loginCmd)
}

func initConfig() {
    if cfgFile != "" {
        // Use config file from the flag.
        viper.SetConfigFile(cfgFile)
    } else {
        home, err := homedir.Dir()
        cobra.CheckErr(err)

        viper.SetConfigName(".pastee")
        viper.SetConfigType("yaml")
        viper.AddConfigPath(home)

        if err := viper.ReadInConfig(); err != nil {
            if _, ok := err.(viper.ConfigFileNotFoundError); ok {

            } else {
                fmt.Println("Error: Configuration file was unable to be read -", err)
                os.Exit(1)
            }
        }
    }

    viper.AutomaticEnv()
}