#/usr/bin/env bash

_container_completions () {
    KAZ_ROOT=$(cd "$(dirname ${COMP_WORDS[0]})"/..; pwd)
    COMPREPLY=()
    . "${KAZ_ROOT}/bin/.commonFunctions.sh"
    setKazVars

    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= 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
	names="${names} ${w}"
    done

    case "$cur" in
	-*)
	    COMPREPLY=( $(compgen -W "-h -n" -- "${cur}" ) ) ;;
	*)
	    local cmd_available="status start stop save"
	    case "${arg_pos}" in
		1)
		    # $1 of container.sh
		    COMPREPLY=($(compgen -W "${cmd_available}" -- "${cur}"))
		    ;;
		*)
		    # $2-* of container.sh
		    [[ " ${cmd_available} " =~ " ${cmd} " ]] || return 0
		    # select set of names
		    local names_set="available"
		    case "${cmd}" in
			status)
			    names_set="available"
			    ;;
			start)
			    names_set="disable"
			    ;;
			stop)
			    names_set="enable"
			    ;;
			save)
			    names_set="validate"
			    ;;
		    esac
		    local available_args=$("${KAZ_ROOT}/bin/kazList.sh" "compose" "${names_set}")
		    # 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 _container_completions container.sh