#/usr/bin/env bash

_orga_gen_completion () {
    KAZ_ROOT=$(cd "$(dirname ${COMP_WORDS[0]})"/../..; pwd)
    ORGA_DIR=$(cd "$(dirname ${COMP_WORDS[0]})"; basename $(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++))
        [[ "${w}" == +* ]] && ((skip++))
    done
    local arg_pos w i addOpt= rmOpt= names=
    ((arg_pos = cword - skip))
    for ((i=1 ; i<card; i++)) ; do
	w="${COMP_WORDS[i]}"
	if [[ "${w}" == -* ]]; then
	    rmOpt="${rmOpt} ${w}"
	    continue
	fi
	if [[ "${w}" == '+'* ]]; then
	    addOpt="${addOpt} ${w}"
	    continue
	fi
	names="${names} ${w}"
    done
    local KAZ_LIST="${KAZ_BIN_DIR}/kazList.sh"
    case "$cur" in
	-*)
	    local available_services item proposal="-h -l" listOpt="available"
	    [ -n "${names}" ] && listOpt="enable ${names}"
	    [[ "${ORGA_DIR}" = "orgaTmpl" ]] || listOpt="enable ${ORGA_DIR%-orga}"
	    available_services=$("${KAZ_LIST}" service ${listOpt} 2>/dev/null | tr ' ' '\n' | sed "s/\(..*\)/-\1/")
	    for item in ${available_services} ; do
		[[ " ${rmOpt} " =~ " ${item} " ]] || proposal="${proposal} ${item}"
	    done
	    COMPREPLY=( $(compgen -W "${proposal}" -- "${cur}" ) )
	    ;;
	'+'*)
	    local available_services item proposal= listOpt="available"
	    [ -n "${names}" ] && listOpt="disable ${names}"
	    [[ "${ORGA_DIR}" = "orgaTmpl" ]] || listOpt="disable ${ORGA_DIR%-orga}"
	    available_services=$("${KAZ_LIST}" service ${listOpt} 2>/dev/null | tr ' ' '\n' | sed "s/\(..*\)/+\1/")
	    for item in ${available_services} ; do
		[[ " ${addOpt} " =~ " ${item} " ]] || proposal="${proposal} ${item}"
	    done
	    COMPREPLY=( $(compgen -W "${proposal}" -- "${cur}" ) )
	    ;;
	*)
	    [[ "${ORGA_DIR}" = "orgaTmpl" ]] || return 0;
	    local available_orga=$("${KAZ_LIST}" "compose" "enable" "orga" 2>/dev/null | sed "s/-orga\b//g")
	    local proposal= item
	    for item in ${available_orga} ; do
		[[ " ${names} " =~ " ${item} " ]] || proposal="${proposal} ${item}"
	    done
	    COMPREPLY=($(compgen -W "${proposal}" -- "${cur}"))
	    ;;
    esac
    return 0
}
complete -F _orga_gen_completion orga-gen.sh
