#!/bin/bash
rootAutoDirs=("__auto/N/"  "__auto/FP/")
rootAutoDirs+=("__auto/F/"  "__auto/E/"  "__auto/T/")

completeSpecificPath() {
    # declare variables
    local curr prev words cword split
    local _item _COMPREPLY
    local method=$1  # WithDirs or WithFiles or "" (nothing)
    
    #go the specific directory
    pushd "${2}" &>/dev/null || return 1

    # init completion and run _filedir inside specific directory
    _init_completion -s || return
    _filedir

    length=${#COMPREPLY[@]}
    declare -a tempArray
    for ((i=0; i<length; i++)); do
        if [[ "${COMPREPLY[$i]}" == __* ]]; then
            continue
        fi
        tempArray+=("${COMPREPLY[$i]}")
    done

    # iterate on original replies
    for _item in "${tempArray[@]}"; do
        if [[ $method == WithDirs && -d "${_item}" ]]; then
            _COMPREPLY+=("${_item}")
        elif [[ $method == WithFiles && -f "${_item}" ]]; then
            _COMPREPLY+=("${_item}")
        elif [[ $method == WithCategorizedFiles ]]; then
            method=""
        fi
        if [[ $method == "" ]]; then
            if [ -d "${_item}" ]; then
                # append a slash if directory
                _COMPREPLY+=("${_item}/")
            else
                _COMPREPLY+=("${_item}")
            fi
        fi
    done

    # add autocategories to category list
    if [[ $method == WithDirs ]]; then
        for _item in ${rootAutoDirs[@]}; do
            pushd "${2}/${_item}" &>/dev/null || continue
            _init_completion -s
            _filedir
            length=${#COMPREPLY[@]}
            for ((i=0; i<length; i++)); do
                _COMPREPLY+=("${COMPREPLY[$i]}")
            done
            popd &>/dev/null
        done
    fi


    popd &>/dev/null

    # if only one reply and it is a directory, don't append a space
    # (I don't know why we must check for length == 2)
    if [ ${#_COMPREPLY[@]} -eq 2 ]; then
        if [[ "${_COMPREPLY}" == */ ]]; then
            compopt -o nospace
        fi
    fi

    # set the values in the right COMPREPLY variable
    COMPREPLY=( "${_COMPREPLY[@]}" )

    # clean up
    unset _COMPREPLY
    unset _item
}
completeSpecificPathWithDirs() {
    completeSpecificPath WithDirs $1
}
completeSpecificPathWithFiles() {
    completeSpecificPath WithFiles $1
}
completeSpecificPathWithCategorizedFiles() {
    completeSpecificPath WithCategorizedFiles $1
}


subcommands="show open run create assign delete copy service --help --version"
subcommands_show="-e -v --all-categories"
options_show="--categories --details --fragment-info --hidden --reverse \
--ipaths --machine -n --no-colors --no-numbers --paths \
--sort=extension --sort=name --sort=none --sort=size --sort=time --sort=atime \
--open --run"
sorttypes="extension name none size time atime"
options_open="--app --hidden --mix -n --reverse --saved-page \
--sort=extension --sort=name --sort=none --sort=size --sort=time --sort=atime \
--show"
options_run="--app --mix -n --reverse --saved-page --sudo --user --show"

#for vitis-sl service
options_get="path lang autosave opener casesensitivity autocategorization \
filespaces"
options_set="path lang autosave opener casesensitivity default"
objects_check="broken-links saved-pages fileformats"

_vitis-sl()
{
    CONFIG=$HOME/.config/vitis-sl/vitis.conf
    if [[ -f "${CONFIG}" ]]; then
        vts_path=$(awk -F "=" '/path/ {print $2}' $CONFIG)
        str_filespaces=$(awk -F "=" '/filespaces/ {print $2}' $CONFIG)
        filespaces=$(echo $str_filespaces | tr ";" "\n")
    fi

    COMPREPLY=()
    curr="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    preprev="${COMP_WORDS[COMP_CWORD-2]}"
    
    if [[ ${COMP_CWORD} == 1 ]] ; then
        COMPREPLY=( $(compgen -W "${subcommands}" -- ${curr}) )
        return 0
    fi

    command="${COMP_WORDS[1]}"
    case "${command}" in
    show)
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            if [[ ${curr} == -* ]]; then
                COMPREPLY=( $(compgen -W "${subcommands_show}" -- ${curr}) )
            else
                completeSpecificPathWithDirs "$vts_path"
            fi
        elif [[ ${COMP_CWORD} -gt 2 ]]; then
            main_opt="${COMP_WORDS[2]}"
            if [[ ${main_opt} == "-v" && ${prev} == "-v" ]]; then
                completeSpecificPathWithCategorizedFiles "${vts_path}"
                return 0
            elif [[ ${main_opt} == "--all-categories" ]]; then
                COMPREPLY=( $(compgen -W "--auto --hidden" -- ${curr}) )
            else  # -e or nothing
                if [[ ${curr} == -* ]]; then
                    COMPREPLY=( $(compgen -W "${options_show}" -- ${curr}) )
                elif [[ ${prev} == "--sort" && ${curr} == "=" ]]; then
                    COMPREPLY=( $(compgen -W "${sorttypes}" -- "") )
                elif [[ ${prev} == "=" && ${preprev} == "--sort" ]]; then
                    COMPREPLY=( $(compgen -W "${sorttypes}" -- ${curr}) )
                elif [[ ${prev} != --*
                     && ${preprev} != "sort"
                     && ${preprev} != "=" ]]
                then
                    completeSpecificPathWithDirs "${vts_path}"
                else
                    COMPREPLY=( $(compgen -W "${options_show}" -- ${curr}) )
                fi
            fi
        fi
        return 0
        ;;
    open)
        if [[ ${COMP_CWORD} -ge 2 ]] ; then
            main_opt="${COMP_WORDS[2]}"
            if [[ ${main_opt} == "-v" && ${prev} == "-v" ]] ; then
                completeSpecificPathWithCategorizedFiles "${vts_path}"
                return 0
            else #-e or nothing
                if [[ ${curr} == -* ]] ; then
                    COMPREPLY=( $(compgen -W "${options_open}" -- ${curr}) )
                elif [[ ${prev} == "--sort" && ${curr} == "=" ]] ; then
                    COMPREPLY=( $(compgen -W "${sorttypes}" -- "") )
                elif [[ ${prev} == "=" && ${preprev} == "--sort" ]] ; then
                    COMPREPLY=( $(compgen -W "${sorttypes}" -- ${curr}) )
                elif [[ ${prev} != --*
                     && ${preprev} != "sort"
                     && ${preprev} != "=" ]]
                then
                    completeSpecificPathWithDirs "${vts_path}"
                else
                    COMPREPLY=( $(compgen -W "${options_open}" -- ${curr}) )
                fi
            fi
        fi
        return 0
        ;;
    run)
        if [[ ${COMP_CWORD} -ge 2 ]]; then
            main_opt="${COMP_WORDS[2]}"
            if [[ ${main_opt} == "-v" && ${prev} == "-v" ]] ; then
                completeSpecificPathWithCategorizedFiles "${vts_path}"
                return 0
            else #-e or nothing
                if [[ ${curr} == -* ]]; then
                    COMPREPLY=( $(compgen -W "${options_run}" -- ${curr}) )
                elif [[ ${prev} == "--sort" && ${curr} == "=" ]]; then
                    COMPREPLY=( $(compgen -W "${sorttypes}" -- "") )
                elif [[ ${prev} == "=" && ${preprev} == "--sort" ]]; then
                    COMPREPLY=( $(compgen -W "${sorttypes}" -- ${curr}) )
                elif [[ ${prev} != --*
                     && ${preprev} != "sort"
                     && ${preprev} != "=" ]]
                then
                    completeSpecificPathWithDirs "${vts_path}"
                else
                    COMPREPLY=( $(compgen -W "${options_run}" -- ${curr}) )
                fi
            fi
        fi
        return 0
        ;;
    copy)
        if [[ ${COMP_CWORD} -ge 3 ]]; then
            if [[ ${COMP_WORDS[2]} == -* ]]; then 
                first_opt="${COMP_WORDS[2]}"
            else
                first_opt="-e"
            fi
            if [[ $first_opt == "-e" ]]; then 
                second_opt="-d"
            else
                second_opt="-e"
            fi
        fi
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            if [[ ${curr} == -* ]]; then
                COMPREPLY=( $(compgen -W "-e -d" -- ${curr}) )
            else
                completeSpecificPathWithDirs "$vts_path"
            fi
        elif [[ ${COMP_CWORD} -ge 3 && ${prev} != '-d' && ${curr} != -* ]]; then
            completeSpecificPathWithDirs "$vts_path"
        elif [[ ${COMP_CWORD} -gt 3 && ${curr} == -* ]]; then
            COMPREPLY=( $(compgen -W $second_opt -- ${curr}) )
        fi
        ;;
    assign)
        main_opt="${COMP_WORDS[2]}"
        if [[ $main_opt != -* ]]; then
            main_opt="-c"
        fi
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            if [[ ${curr} == -* ]]; then
                COMPREPLY=( $(compgen -W "-c -d -f -i -v" -- ${curr}) )
                return 0
            else 
                completeSpecificPathWithDirs "$vts_path"
                return 0
            fi
        elif [[ ${COMP_CWORD} -ge 3 ]]; then
            if [[ $main_opt == "-f" ]]; then
                if [[ ${preprev} == "-f" ]]; then
                    COMPREPLY=( $(compgen -W "-n" -- ${curr}) )
                    return 0
                fi
            elif [[ $main_opt == "-v" ]]; then
                if [[ ${preprev} == "-v" ]]; then
                    COMPREPLY=( $(compgen -W "-n" -- ${curr}) )
                    return 0
                elif [[ ${prev} == "-v" ]]; then
                    completeSpecificPathWithCategorizedFiles "${vts_path}"
                    return 0
                elif [[ ${preprev} == "-n" ]]; then
                    COMPREPLY=( $(compgen -W "--number" -- ${curr}) )
                    return 0
                fi
            else
                if [[ ${prev} == "-c" ]]; then
                    completeSpecificPathWithDirs "$vts_path"
                    return 0
                fi
                if [[ ${prev} == "-s" ]]; then
                    completeSpecificPathWithDirs "${vts_path}"
                    return 0
                fi
                if [[ ${preprev} == "-s" ]]; then
                    COMPREPLY=( $(compgen -W "--local --global" -- ${curr}) )
                    return 0
                fi
                if [[ ${prev} == "-f" ]]; then
                    return 0
                fi
                if [[ ${prev} == "-v" ]]; then
                    completeSpecificPathWithCategorizedFiles "${vts_path}"
                    return 0
                fi
                second_opts="-a -e -d -f -i -n -s -v"
                second_opt=""
                for sec_opt in -a -e -d -f -i -n -s
                do
                    for (( index=1; index<`expr ${COMP_CWORD}-1`; index++ ))
                    do
                        if [[ ${COMP_WORDS[$index]} == $sec_opt ]]; then
                            second_opt=$sec_opt
                            break
                        fi
                    done
                done
                if [[ ${prev} == "--to" ]]; then
                    COMPREPLY=($(compgen -W "${filespaces}" -- ${curr}) )
                    return 0
                fi
                if [[ ${curr} == -* && $second_opt == "" ]]; then
                    COMPREPLY=($(compgen -W "${second_opts}" -- ${curr}) )
                    return 0
                fi
                options_dir1="--save --to --as"
                options_dir2="--save --to --as -c"
                if [[ $prev == "--as" ]]; then
                    completeSpecificPathWithDirs "$vts_path"
                fi
                if [[ $second_opt == "-d" && $main_opt == "-c" ]]; then
                    COMPREPLY=($(compgen -W "$options_dir1" -- ${curr}) )
                    return 0
                elif [[ $second_opt == "-d" && $main_opt == "-d" ]]; then
                    COMPREPLY=($(compgen -W "$options_dir2" -- ${curr}) )
                    return 0
                fi
                options_file="--save --to --start --finish --fragname"
                if [[ $second_opt == "-f" ]]; then
                    COMPREPLY=($(compgen -W "${options_file}" -- ${curr}) )
                    return 0
                fi
                if [[ $main_opt == "-c" ]]; then
                    if [[ $second_opt == "-e" || $second_opt == "" ]]; then
                        completeSpecificPathWithDirs "${vts_path}"
                        return 0
                    fi
                fi
            fi
        fi
        ;;
    create)
        if [[ ${COMP_CWORD} -eq 2 && ${curr} == -* ]]; then
            COMPREPLY=($(compgen -W "-c" -- ${curr}) )
            return 0
        elif [[ ${COMP_CWORD} -ge 2 && ${curr} != -* ]]; then
            completeSpecificPathWithDirs "${vts_path}"
            return 0
        fi
        ;;
    delete)
        if [[ ${COMP_CWORD} -ge 3 ]]; then
            if [[ ${COMP_WORDS[2]} == -* ]]; then 
                first_opt="${COMP_WORDS[2]}"
            else
                first_opt="-c"
            fi
            if [[ $first_opt == "-c" ]]; then 
                second_opt="-f"
            fi
        fi

        if [[ ${COMP_CWORD} -eq 2 && ${curr} == -* ]]; then
            COMPREPLY=( $(compgen -W "-c -v" -- ${curr}) )
            return 0
        elif [[ ${COMP_CWORD} -eq 2 && ${curr} != -* ]] ; then
            completeSpecificPathWithDirs "$vts_path"
        elif [[ ${COMP_CWORD} -ge 3 ]]; then
            if [[ ${first_opt} == "-v" && ${curr} != -* ]]; then
                completeSpecificPathWithCategorizedFiles "$vts_path"
                return 0
            elif [[ ${first_opt} == "-v" && ${curr} == -* ]]; then
                COMPREPLY=( $(compgen -W "--number" -- ${curr}) )
                return 0
            elif [[ ${first_opt} == "-c" ]]; then
                if [[ ${preprev} == "-f" ]]; then
                    COMPREPLY=( $(compgen -W "--number" -- ${curr}) )
                    return 0
                elif [[ ${prev} != "-f" ]]; then
                    if [[ ${curr} == -* ]]; then
                        COMPREPLY=( $(compgen -W "-f --force" -- ${curr}) )
                        return 0
                    else
                        completeSpecificPathWithDirs "$vts_path"
                    fi
                else
                    category=${preprev}
                    completeSpecificPathWithFiles "${vts_path}/${category}"
                fi
            fi
        fi
        ;;
    service)
        service_actions="add check disregard get set prioritize reset"
        if [[ ${COMP_CWORD} -eq 2 ]]; then
            COMPREPLY=( $(compgen -W "${service_actions}" -- ${curr}) )
            return 0
        fi
        if [[ ${COMP_CWORD} -ge 3 ]]; then
            action="${COMP_WORDS[2]}"
            case "${action}" in
            add)
                COMPREPLY=( $(compgen -W "filespace" -- ${curr}) )
                return 0
                ;;
            prioritize)
                if [[ ${COMP_CWORD} -eq 3 ]]; then
                    COMPREPLY=( $(compgen -W "filespace" -- ${curr}) )
                elif [[ ${COMP_CWORD} -eq 4 ]]; then
                    #echo filespaces: ${filespaces}
                    COMPREPLY=($(compgen -W "${filespaces}" -- ${curr}) )
                fi
                return 0
                ;;
            disregard)
                if [[ ${COMP_CWORD} -eq 3 ]]; then
                    COMPREPLY=( $(compgen -W "filespace" -- ${curr}) )
                elif [[ ${COMP_CWORD} -eq 4 ]]; then
                    COMPREPLY=($(compgen -W "${filespaces}" -- ${curr}) )
                fi
                return 0
                ;;
            get)
                COMPREPLY=( $(compgen -W "${options_get}" -- ${curr}) )
                return 0
                ;;
            set)
                COMPREPLY=( $(compgen -W "${options_set}" -- ${curr}) )
                return 0
                ;;
            check)
                if [[ ${COMP_CWORD} -eq 3 ]]; then
                    COMPREPLY=( $(compgen -W "${objects_check}" -- ${curr}) )
                    return 0
                elif [[ ${COMP_CWORD} -ge 4 ]]; then
                    if [[ ${COMP_CWORD} -gt 4 && ${prev} == "-c" ]]; then
                        completeSpecificPathWithDirs "${vts_path}"
                        return 0
                    fi
                    object="${COMP_WORDS[3]}"
                    if [[ $object == "broken-links" ]]; then
                        flags="-c --fix --interactive"
                        COMPREPLY=( $(compgen -W "${flags}" -- ${curr}) )
                        return 0
                    elif [[ $object == "fileformats" ]]; then
                        flags="-c --fix --interactive"
                        COMPREPLY=( $(compgen -W "${flags}" -- ${curr}) )
                        return 0
                    elif [[ $object == "saved-pages" ]]; then
                        flags="-c --fix --fresh --interactive"
                        COMPREPLY=( $(compgen -W "${flags}" -- ${curr}) )
                        return 0
                    fi
                fi
                ;;
            esac
        fi
        ;;
    
    esac

    return 0
}

complete -o default -F _vitis-sl vitis-sl
