package completion

import (
	"fmt"

	"github.com/pkg/errors"
	"github.com/smallstep/cli/flags"
	"github.com/urfave/cli"
	"go.step.sm/cli-utils/command"
	"go.step.sm/cli-utils/errs"
)

func init() {
	cmd := cli.Command{
		Name:      "completion",
		Usage:     "print the shell completion script",
		UsageText: "**step completion** <shell>",
		Description: `**step completion** command prints the shell completion script.

## POSITIONAL ARGUMENTS

<shell>
: The shell program. Either bash or zsh.

## EXAMPLES

Add bash completion for the current user.
'''
$ step completion bash >> ~/.bash_completion
'''
`,
		Flags: []cli.Flag{
			flags.HiddenNoContext,
		},
		Action: Completion,
		BashComplete: func(c *cli.Context) {
			if c.NArg() > 0 {
				return
			}
			fmt.Println("bash")
			fmt.Println("zsh")
			fmt.Println("fish")
		},
	}

	command.Register(cmd)
}

var bash = `# bash completion for step
_step_cli_bash_autocomplete() {
	local cur opts base
	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	if [[ "$cur" == "-"* ]]; then
		opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} ${cur} --generate-bash-completion )
	else
		opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
	fi
	COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
	return 0
}

complete -o bashdefault -o default -F _step_cli_bash_autocomplete step

`

var zsh = `# zsh completion for step
#compdef step

_step() {

  local -a opts
  local cur
  cur=${words[-1]}
  if [[ "$cur" == "-"* ]]; then
    opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} ${cur} --generate-bash-completion)}")
  else
    opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} --generate-bash-completion)}")
  fi

  if [[ "${opts[1]}" != "" ]]; then
    _describe 'values' opts
  else
    _files
  fi

  return
}

compdef _step step

`

func Completion(ctx *cli.Context) error {
	if err := errs.NumberOfArguments(ctx, 1); err != nil {
		return err
	}

	shell := ctx.Args().First()

	switch shell {
	case "bash":
		fmt.Print(bash)
	case "zsh":
		fmt.Print(zsh)
	case "fish":
		fmt.Print(ctx.App.ToFishCompletion())
	default:
		return errors.Errorf("unsupported shell %s", shell)
	}

	return nil
}
