package commands

import (
	"fmt"
	"os"
	"os/exec"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"github.com/contiamo/dev/cli/config"
)

func init() {
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(startCmd)
	rootCmd.AddCommand(stopCmd)
	rootCmd.AddCommand(restartCmd)
	rootCmd.AddCommand(restoreCmd)
	rootCmd.AddCommand(snapshotCmd)
	rootCmd.AddCommand(testCmd)
	rootCmd.AddCommand(dockerAuthCmd)
	rootCmd.AddCommand(prPreviewCmd)
	rootCmd.AddCommand(pullCmd)
	rootCmd.AddCommand(listServicesCmd)
	rootCmd.AddCommand(logsCmd)
	rootCmd.AddCommand(initCmd)
	rootCmd.AddCommand(showConfigCmd)
	rootCmd.AddCommand(statusCmd)
	rootCmd.PersistentFlags().Bool("verbose", false, "enable debug logging")
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version data",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Fprintln(cmd.OutOrStdout(), "Version: "+config.Version)
		fmt.Fprintln(cmd.OutOrStdout(), "Commit: "+config.GitCommit)
	},
}

// rootCmd represents the main command when the binary is called without any subcommands
var rootCmd = &cobra.Command{
	Use:     "localdev",
	Short:   "cross-platform localdev environment for the Contiamo DataHub",
	Long:    rootHelp,
	Example: rootExamples,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
		err = setLogLevel(cmd)
		if err != nil {
			return err
		}

		err = config.Setup()
		if err != nil {
			return err
		}

		logrus.Debugf("localdevroot found set to: %q", config.LocaldevRoot())
		return checkDependencies(cmd)
	},
}

// Execute starts the command
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func setLogLevel(cmd *cobra.Command) error {
	verbose, err := cmd.Flags().GetBool("verbose")
	if err != nil {
		return err
	}

	if verbose {
		logrus.SetLevel(logrus.DebugLevel)
	}

	return nil
}

func checkDependencies(cmd *cobra.Command) error {
	deps := []string{"docker", "docker-compose", "gcloud", "git"}

	for _, dependency := range deps {
		path, err := exec.LookPath(dependency)
		if err != nil {
			return err
		}
		logrus.Debugf("%s found at: %q", dependency, path)
	}

	return nil
}
