__cmd_query() {
    local -a arr=( "$@" )
    local query i
    for (( i = 0 ; i < ${#arr[@]} ; i++ )) do
        [[ "${arr[i]}" == -* ]] && continue
        if [ "${arr[i+2]}" ];then
            query="$query ${arr[i]}=${arr[i+2]}"
        fi
        ((i+=2))
    done
    echo "$query"
}


__databrowser() {
    local options args facets extra
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    cur="${COMP_WORDS[COMP_CWORD],,}"
    let num=$1
    if [ $num -eq 1 ];then
        cmd_args="${COMP_WORDS[@]:$1:COMP_CWORD-1}"
    else
        cmd_args="${COMP_WORDS[@]:$1:COMP_CWORD-2}"
    fi
    query="$(__cmd_query $cmd_args)"
    [[ -z "$cur" ]] && extra=--relevant-only
    if [[ "$cur" == "=" ]]; then
        options="$(freva databrowser --facet $prev $query | sed -e 's/[^:]*: //' -e 's/,/ /g')"
        #don't consider this for selection of possible auto-complete word
    elif [ "$prev" == "=" ]; then
        facet="${COMP_WORDS[COMP_CWORD-2]}"
        options="$(freva databrowser ${extra} --facet $facet $query $facet=${cur}* | sed -e 's/[^:]*: //' -e 's/,/ /g')"
    elif [ "$prev" == "--facet" ]; then
        options="$(freva databrowser ${extra} --attributes $query | sed  -e 's/,//g')"
    elif [ "$(echo $cur |cut -c1)" == "-" ]; then
        for arg in ${cmd_args[@]};do
            if [ "$(echo $arg|cut -c1)" = "-" ];then
                flags="$flags $arg"
            fi
        done
        options="$(python -m freva.cli --shell bash --flags-only freva databrowser $flags)"
    else
        options="$(freva databrowser ${extra} --attributes $query | sed  -e 's/,/=/g')="
    fi
    echo $options
}

__plugin() {

    local -a plugins args flags
    local plugin
    let num=$1
    if [ $COMP_CWORD -lt 2 ];then
        cmd_args="${COMP_WORDS[@]:$1:COMP_CWORD-1}"
    else
        cmd_args="${COMP_WORDS[@]:$1:COMP_CWORD-1}"
    fi
    if [ $num -ge $COMP_CWORD ];then
        if [ "$(echo $cur |cut -c1)" == "-" ]; then
            options="$(python -m freva.cli --shell bash --flags-only freva plugin)"
        else
            options="$(python -m freva.cli --shell bash --strip freva plugin)"
        fi
        echo $options
        return
    fi
    if [ "$(echo $cur |cut -c1)" == "-" ]; then
        # Search for flags only
        for arg in ${cmd_args[@]};do
            if [ "$(echo $arg|cut -c1)" = "-" ];then
                flags="$flags $arg"
            fi
        done
        options="$(python -m freva.cli --shell bash --flags-only freva plugin $flags)"
        echo $options
    fi
    for comp in ${cmd_args[@]};do
        if [ ! "$(echo $comp|cut -c1)" == "-" ];then
            # First are not startig with '-' should be the plugin
            plugin=$comp
            break
        fi
    done
    if [ -z "$plugin" ];then
        cur=""
        options="$(python -m freva.cli --shell bash --strip freva plugin)"
        echo $options
        return
    fi
    # We do have a plugin
    opts="$(python -m freva.cli --shell bash --strip freva plugin $cmd_args)"
    for opt in $opts;do
        if [ "${cmd_args##*${opt}*}" ];then
            echo ${opt}=
        fi
    done
}

__freva_databrowser() {

    options="$(__databrowser $1)"
    cur="${COMP_WORDS[COMP_CWORD],,}"
    if [[ "$cur" == "=" ]]; then
        cur=
    fi
    COMPREPLY=( $(compgen -W "${options}" -- "$cur"  ) )
}

__freva_plugin() {

    options="$(__plugin $1)"
    cur="${COMP_WORDS[COMP_CWORD]}"
    if [ "$cur" == "=" ]; then
        cur=
    elif [ "$cur" == "-" ] && [ -z "$(echo $options|grep - '-')" ];then
        # Something is odd with compgen, I have no clue why this happens
       cur=
    fi
    COMPREPLY=( $(compgen -W "${options}" -- "$cur"  ) )
}


__freva() {

    local options args
    if [ "${COMP_WORDS[1]}" == "databrowser" ];then
        __freva_databrowser 2
    elif [ "${COMP_WORDS[1]}" == "plugin" ];then
        __freva_plugin 2
    else
        __show_help
    fi
}

__show_help() {
    local cmd=$1
    if [ -z "$cmd" ];then
        cmd=freva
    fi
    if [ "$cmd" == freva-databrowser ];then
        __freva_databrowser 1
    elif [ "$cmd" == freva-plugin ];then
        __freva_plugin 1
    else
        options="$(python -m freva.cli --shell bash --flags-only $cmd "${COMP_WORDS[@]:1:COMP_CWORD-1}")"
        cur="$(echo "${COMP_WORDS[COMP_CWORD]}" | tr '[:upper:]' '[:lower:]')"
        COMPREPLY=( $(compgen -W "${options}" -- "$cur"  ) )
    fi
}


complete -o nospace -o default -F __freva freva
complete -o nospace -o default -F __show_help freva-history
complete -o nospace -o default -F __show_help freva-esgf
complete -o nospace -o default -F __show_help freva-crawl-my-data
complete -o nospace -o default -F __show_help freva-databrowser
complete -o nospace -o default -F __show_help freva-plugin
