#compdef sorcery

# Define global values
# _sorcery_cmds_needs_spells
if (( ! $+_sorcery_cmds_needs_spell )); then
    typeset -g _sorcery_cmds_needs_spell
    _sorcery_cmds_needs_spell=(
	exile unexile add-queue remove-queue
    )
fi

# _sorcery_cmds_need_installed_spells
if (( ! $+_sorcery_cmds_needs_installed_spell )); then
    typeset -g _sorcery_cmds_needs_installed_spell
    _sorcery_cmds_needs_installed_spell=(
	hold unhold	
    )
fi

# _sorcery_cmds
if (( ! $+_sorcery_cmds )); then
    typeset -g _sorcery_cmds
    _sorcery_cmds=(
	$_sorcery_cmds_needs_installed_spell $_sorcery_cmds_needs_spell
	update system-update queue upgrade rebuild queue-security
    )
fi

# main completion function
_sorcery () {
 
  _arguments -C \
  '(--help)-h[show help]' \
  '(-h)--help' \
  '(--version)-v[Print the sorcery version]' \
  '(-v)--version' \
  '*::sorcery command:_sorcery_command' 
#  _arguments -s '*::sorcery command:_sorcery_command'
}

# @param 1 search string
# @param 2 strings array
# @return exit code 0 (true) or 1 (false)
_sorcery_is_in_array() {
  local SEARCHING_STRING=$1
  local TARGET_ARRAY=$2

  for i in ${=TARGET_ARRAY} ; do
      if [[ ${i} == ${SEARCHING_STRING} ]]; then
	  return 0
      fi
  done;
  return 1
}

# Define sorcery command dispatch function.
(( $+functions[_sorcery_command] )) ||
_sorcery_command () {

  # complete command
  if (( CURRENT == 1 )); then
    compadd ${_sorcery_cmds}

  # complete commands argument
  elif (( CURRENT == 2 )); then

    local cmd=${words[1]}

    # start argument completion
    if ( _sorcery_is_in_array ${cmd} "${_sorcery_cmds_needs_spell}"; ) then
	_spells
    elif ( _sorcery_is_in_array ${cmd} "${_sorcery_cmds_needs_installed_spell}" ) ; then
	_installed_spells
    else
      false
    fi
    
  # "sorcery" doesn't need 3rd (or more) argument.
  else
    false
  fi
}

_sorcery "$@"
