#/usr/bin/env bash

_kazDockerNet_completion () {
    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

    local cword=${COMP_CWORD} cur=${COMP_WORDS[COMP_CWORD]}
    case "$cur" in
	-*)
	    COMPREPLY=( $(compgen -W "-h -n" -- "${cur}" ) )
	    ;;
	*)
	    local cmd_available="list add"
	    case "${cword}" in
		1)
		    COMPREPLY=($(compgen -W "${cmd_available}" -- "${cur}"))
		    ;;
		*)
		    [[ "${cmd}" = "add" ]] || return 0
		    local available_args=$("${KAZ_BIN_DIR}/kazList.sh" "compose" "available" 2>/dev/null)
		    local used=$("${KAZ_BIN_DIR}/kazDockerNet.sh" "list" | grep "name:" | sed -e "s%\bname:\s*%%" -e "s%\bbridge\b\s*%%" -e "s%Net\b%%g")
		    local proposal item
		    for item in ${available_args} ; do
			[[ " ${names} " =~ " ${item} " ]] || [[ " ${used} " =~ " ${item} " ]] || proposal="${proposal} ${item}"
		    done
		    COMPREPLY=($(compgen -W "${proposal}" -- "${cur}"))
		    ;;
	    esac
	    ;;
    esac
    return 0
}
complete -F _kazDockerNet_completion kazDockerNet.sh
