package app

import (
	"os"
	"os/exec"
	"strings"

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

// translators: `abra app config` aliases. use a comma separated list of
// aliases with no spaces in between
var appConfigAliases = i18n.G("cfg")

var AppConfigCommand = &cobra.Command{
	// translators: `app config` command
	Use:     i18n.G("config <domain> [flags]"),
	Aliases: strings.Split(appConfigAliases, ","),
	// translators: Short description for `app config` command
	Short:   i18n.G("Edit app config"),
	Example: i18n.G("  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.Fatal(i18n.G("cannot find app with name %s", appName))
		}

		ed, ok := os.LookupEnv("EDITOR")
		if !ok {
			edPrompt := &survey.Select{
				Message: i18n.G("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)
		}
	},
}
