package cmd

import (
	"github.com/spf13/cobra"
	"github.com/twpayne/go-shell"
)

type cdCmdConfig struct {
	Command string   `mapstructure:"command"`
	Args    []string `mapstructure:"args"`
}

func (c *Config) newCDCmd() *cobra.Command {
	cdCmd := &cobra.Command{
		Use:     "cd",
		Short:   "Launch a shell in the source directory",
		Long:    mustLongHelp("cd"),
		Example: example("cd"),
		RunE:    c.runCDCmd,
		Args:    cobra.NoArgs,
		Annotations: map[string]string{
			createSourceDirectoryIfNeeded: "true",
			doesNotRequireValidConfig:     "true",
			requiresWorkingTree:           "true",
			runsCommands:                  "true",
		},
	}

	return cdCmd
}

func (c *Config) runCDCmd(cmd *cobra.Command, args []string) error {
	cdCommand, cdArgs := c.cdCommand()
	return c.run(c.WorkingTreeAbsPath, cdCommand, cdArgs)
}

func (c *Config) cdCommand() (string, []string) {
	cdCommand := c.CD.Command
	cdArgs := c.CD.Args

	if cdCommand != "" {
		return cdCommand, cdArgs
	}

	cdCommand, _ = shell.CurrentUserShell()
	return parseCommand(cdCommand, cdArgs)
}
