#!/bin/bash

_appsh_find() {
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && echo $1 && return; done
}

_appsh_method_groups=(
    "instance"
    "conf"
    "operate"
    )

_appsh_methods=(
    "install"
    )

_appsh_resolvers=(
    "file"
    "maven"
    )

_appsh_parse_opts() {
  local prev=""
  local has_method
  for ((i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do
    local curr=${COMP_WORDS[$i]}
    if [ "$prev" == -n ]
    then
      echo "local has_n=$curr"
    elif [ "$prev" == -i ]
    then
      echo "local has_i=$curr"
    fi

    has_method_group="$has_method_group$(_appsh_find "$curr" ${_appsh_method_groups[@]})"
    has_method="$has_method$(_appsh_find "$curr" ${_appsh_methods[@]})"
    prev="${COMP_WORDS[$i]}"
  done
  echo "local has_method_group='$has_method_group'"
  echo "local has_method='$has_method'"

  case "${COMP_WORDS[COMP_CWORD]}" in
    -*)
      echo "local in_option=yes"
      ;;
  esac
}

_complete_appsh() {
  COMPREPLY=()
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local prev="${COMP_WORDS[COMP_CWORD-1]}"
  local opts=""

  local x=`_appsh_parse_opts`
  eval "$x"
#  set | grep ^has_

  if [ $COMP_CWORD == 1 ]
  then
    opts="${_appsh_method_groups[@]}"
    opts="$opts"
    if [ "$in_option" = "yes" ]
    then
    opts="-n $opts"
    fi
    COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
    return 0
  fi

  case "$prev" in
    -n)
      values=$(./app instance list -P name)
      COMPREPLY=($(compgen -W "$values" -- ${cur}))
      return 0
      ;;
    -i)
      if [ -n "$has_n" ]
      then
        values=$(./app instance list -n $has_n -P instance)
        COMPREPLY=($(compgen -W "$values" -- ${cur}))
        return 0
      fi
      ;;
    -r)
      COMPREPLY="${_appsh_resolvers[@]}"
      COMPREPLY=($(compgen -W "$COMPREPLY" -- ${cur}))
      return
      ;;
    -u)
      COMPREPLY=($(compgen -o filenames -f -- ${cur}))
      return
      ;;
  esac

  if [ -n "$has_n" -a -z "$has_i" ]
  then
   opts="$opts -i"
  fi

  has_method_group=$has_method_group
  has_method=$has_method
  case "$has_method_group" in
    instance)
      if [ -z $has_method ]
      then
        opts="$opts install list list-versions set-current"
      else
        case "$has_method" in
          install)
            opts="$opts -r -u"
            ;;
        esac
      fi
      ;;
  esac

  COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
  set +x
}

complete -F _complete_appsh app