package app

import (
	"os"
	"os/exec"

	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/log"
	"github.com/AlecAivazis/survey/v2"
	"github.com/spf13/cobra"
)

var AppConfigCommand = &cobra.Command{
	Use:     "config <app> [flags]",
	Aliases: []string{"cfg"},
	Short:   "Edit app config",
	Example: "  abra config 1312.net",
	Args:    cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		files, err := appPkg.LoadAppFiles("")
		if err != nil {
			log.Fatal(err)
		}

		appName := args[0]
		appFile, exists := files[appName]
		if !exists {
			log.Fatalf("cannot find app with name %s", appName)
		}

		ed, ok := os.LookupEnv("EDITOR")
		if !ok {
			edPrompt := &survey.Select{
				Message: "which editor do you wish to use?",
				Options: []string{"vi", "vim", "nvim", "nano", "pico", "emacs"},
			}
			if err := survey.AskOne(edPrompt, &ed); err != nil {
				log.Fatal(err)
			}
		}

		c := exec.Command(ed, appFile.Path)
		c.Stdin = os.Stdin
		c.Stdout = os.Stdout
		c.Stderr = os.Stderr
		if err := c.Run(); err != nil {
			log.Fatal(err)
		}
	},
}
