package cmd

import (
	"axolotl/store"
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var aliasDesc string

var aliasCmd = &cobra.Command{
	Use: "alias [name] [command]", Short: "Manage aliases", Args: cobra.MaximumNArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		w := cmd.OutOrStdout()
		if len(args) == 0 {
			if aliases, err := cfg.ListAliases(); err == nil {
				PrintAliases(w, aliases, jsonFlag)
			}
			return
		}
		if len(args) == 1 {
			a, err := cfg.GetAlias(args[0])
			if err != nil {
				fmt.Fprintln(os.Stderr, "alias not found:", args[0])
				os.Exit(1)
			}
			fmt.Println(a.Command)
			return
		}
		if err := cfg.SetAlias(&store.Alias{Name: args[0], Command: args[1], Description: aliasDesc}); err != nil {
			fmt.Fprintln(os.Stderr, "failed to set alias:", err)
		} else {
			PrintAction(w, "Alias set", args[0], false)
		}
	},
}

var aliasDelCmd = &cobra.Command{
	Use: "del <name>", Short: "Delete an alias", Args: cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		if err := cfg.DeleteAlias(args[0]); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		PrintAction(cmd.OutOrStdout(), "Alias deleted", args[0], false)
	},
}

func init() {
	rootCmd.AddCommand(aliasCmd)
	aliasCmd.AddCommand(aliasDelCmd)
	aliasCmd.Flags().StringVar(&aliasDesc, "desc", "", "description for the alias")
}
