#compdef sk

(( $+functions[_sk_commands] )) ||
_sk_commands() {
  local -a commands
  commands=(
    'add:Add a new template'
    'apply:Apply a template'
    'edit:Edit an existing template'
    'list:List all templates'
    'remove:Remove an existing template'
    'rename:Rename an existing template'
    'help:Print this message or the help of the given subcommand(s)'
  )
  _describe 'sk commands' commands
}

_sk_groups() {
  local -a groups=(${(f)"$(find -L "${HOME}/.skeleton" -type f -exec lr -s {} + | cut -d'.' -f1 | unique)"})
  _values 'groups' $groups
}

_sk() {
  local context state line curcontext="$curcontext"
  typeset -A opt_args
  local ret=1

  _arguments -C \
    '(- 1 *)'{-V,--version}'[show version information]' \
    '(- 1 *)'{-h,--help}'[show help message]' \
    '1: :_sk_commands' \
    '*:: :->command_args' \
  && ret=0

  case "$state" in
    (command_args)
      case "$line[1]" in
        (add)
          _values 'add' \
            {-e,--editor}'[Editor to edit the file with]:EDITOR:' \
            {-w,--with-template}'[Pre-populate the file with a template]' \
            {-f,--from-file}'[From file]:FROM_FILE:' \
            {-h,--help}'[Print help]' \
            && ret=0
            ;;
        (apply)
          _values 'apply' \
            {-g,--groups}'[Groups to filter templates by]:GROUPS:_sk_groups' \
            {-i,--interactive}'[Interactive mode]' \
            {-o,--overwrite}'[Overwrite existing files]' \
            {-h,--help}'[Print help]' \
            && ret=0
            ;;
        (edit)
          _values 'edit' \
            {-e,--editor}'[Editor to edit the file with]:EDITOR:' \
            {-h,--help}'[Print help]' \
            && ret=0
            ;;
        (help)
            _wanted expl 'commands' compadd _sk_commands
            ;;
        (list)
          _values 'list' \
            {-g,--groups}'[Groups to filter templates by]:GROUPS:_sk_groups' \
            {-h,--help}'[Print help]' \
            && ret=0
            ;;
        (remove)
          _values 'remove' \
            {-h,--help}'[Print help]' \
          && ret=0
          ;;
        (rename)
          _values 'rename' \
            {-h,--help}'[Print help]' \
          && ret=0
          ;;
        esac
      ;;
  esac
  return
}

_sk "$@"
