#compdef gaze

# Define global values
# _gaze_cmds_needs_spells
if (( ! $+_gaze_cmds_needs_spell )); then
    typeset -g _gaze_cmds_needs_spell
    _gaze_cmds_needs_spell=(
        service provides what short where website version versions license
	sources source_urls history sum export import section maintainer
	grimoire grimoires html voyeur depends dependencies
	DETAILS PREPARE CONFLICTS CONFIGURE DEPENDS HISTORY TRIGGERS PROVIDES
	PRE_BUILD BUILD POST_BUILD PRE_INSTALL POST_INSTALL
	RE_REMOVE POST_REMOVE
    )
fi

# _gaze_cmds_need_installed_spells
if (( ! $+_gaze_cmds_needs_installed_spell )); then
    typeset -g _gaze_cmds_needs_installed_spell
    _gaze_cmds_needs_installed_spell=(
	install installed compile md5sum install-full install-spell
	size checkmd5s
    )
fi

# _gaze_cmds
if (( ! $+_gaze_cmds )); then
    typeset -g _gaze_cmds
    _gaze_cmds=(
	$_gaze_cmds_needs_installed_spell $_gaze_cmds_needs_spell
	alien from search newer older prune pam orphans
	install-queue remove-queue show-held show-exiled activity
    )
fi

# main completion function
_gaze () {
    _arguments -s '*::gaze command:_gaze_command'
}

# @param 1 search string
# @param 2 strings array
# @return exit code 0 (true) or 1 (false)
_gaze_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 gaze command dispatch function.
(( $+functions[_gaze_command] )) ||
_gaze_command () {
    	    
  # complete command
  if (( CURRENT == 1 )); then
    compadd ${_gaze_cmds}

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

    local cmd=${words[1]}

    # start argument completion
    if [[ $cmd == "from" ]]; then
	_files
    elif ( _gaze_is_in_array ${cmd} "${_gaze_cmds_needs_spell}" ) ; then
	_spells
    elif ( _gaze_is_in_array ${cmd} "${_gaze_cmds_needs_installed_spell}" ) ; then
	_installed_spells
    else
      false
    fi
    
  # "gaze" dosen't need 3rd (or more) argument.
  else
    false
  fi
}

_gaze "$@"
