#/usr/bin/env bash

_kazList_completions () {
    #KAZ_ROOT=$(cd "$(dirname ${COMP_WORDS[0]})"/..; pwd)
    COMPREPLY=()
    local cword=${COMP_CWORD} cur=${COMP_WORDS[COMP_CWORD]} card=${#COMP_WORDS[@]} i w skip=0
    for ((i=1 ; i<cword; i++)) ; do
	w="${COMP_WORDS[i]}"
        [[ "${w}" == -* ]] && ((skip++))
    done
    local arg_pos w i cmd= opt= names=
    ((arg_pos = cword - skip))
    for ((i=1 ; i<card; i++)); do
	w="${COMP_WORDS[i]}"
	if [ -z "${cmd}" ]; then
	    [[ "${w}" == -* ]] || cmd="${w}"
	    continue
	fi
	if [ -z "${opt}" ]; then
	    [[ "${w}" == -* ]] || opt="${w}"
	    continue
	fi
	names="${names} ${w}"
    done
    #(echo "A cword:${cword} / arg_pos:${arg_pos} / card:${card} / cur:${cur} / cmd:${cmd} / opt:${opt} / names:${names} " >> /dev/pts/1)

    case "${cur}" in
	-*)
	    COMPREPLY=($(compgen -W "-h --help" -- "${cur}"))
	    ;;
	*)
	    local cmd_available="compose service"
	    local opt_available="available validate enable disable status"
	    case "${arg_pos}" in
		1)
		    # $1 of kazList.sh
		    COMPREPLY=($(compgen -W "${cmd_available}" -- "${cur}"))
		    ;;
		2)
		    # $2 of kazList.sh
		    COMPREPLY=($(compgen -W "${opt_available}" -- "${cur}"))
		    ;;
		*)
		    # $3-* of kazList.sh
		    [[ " ${cmd_available} " =~ " ${cmd} " ]] || return 0
		    # select set of names
		    local names_set="${opt}"
		    local available_args
		    case "${cmd}" in
			service)
			    case "${names_set}" in
				available|validate)
				    return 0
				    ;;
				*)
				    available_args=$("${COMP_WORDS[0]}" "compose" "enable" "orga" 2>/dev/null)
				    ;;
			    esac
			    ;;
			compose)
			    case "${names_set}" in
				validate|enable|disable)
				    ;;
			   	*)
				    names_set="available"
				    ;;
			    esac
			    available_args=$("${COMP_WORDS[0]}" "${cmd}" "${names_set}")
			    ;;
		    esac
		    # remove previous selected target
		    local proposal item
		    for item in ${available_args} ; do
			[[ " ${names} " =~ " ${item} " ]] || proposal="${proposal} ${item}"
		    done
		    COMPREPLY=($(compgen -W "${proposal}" -- "${cur}"))
		    ;;
	    esac
    esac
    return 0
}

complete -F _kazList_completions kazList.sh
