#!/bin/bash

Complete_Format() {
    local COMPILER=$(ufo --compiler)
    local JSON="/etc/amalthea-${COMPILER}/fileformats.json"
    declare -a FORMATS
    IFS=$'\n' FORMATS=($(ufo --all-formats))
    compopt -o filenames
    local CURR="${COMP_WORDS[COMP_CWORD]}"
    local FOR_SEARCHING
    if [[ "$CURR" =~ ^\"(.*)$ ]]; then
        FOR_SEARCHING="${BASH_REMATCH[1]}"
    elif [[ "$CURR" =~ ^\'(.*)$ ]]; then
        FOR_SEARCHING="${BASH_REMATCH[1]}"
    else
        DECODED_CURR="${CURR//\\ / }"
        FOR_SEARCHING="${DECODED_CURR}"
        if [[ "${FOR_SEARCHING: -1}" == '\' ]]; then
            FOR_SEARCHING="${FOR_SEARCHING::-1}"
        fi
    fi

    COMPREPLY=()
    local ELEM
    for ELEM in "${FORMATS[@]}"; do
        if [[ "$ELEM" == "$FOR_SEARCHING"* ]]; then
            COMPREPLY+=( "$ELEM" )
        fi
    done
}


_ufo() {
    COMPREPLY=()
    local CURR="${COMP_WORDS[COMP_CWORD]}"
    local FIRST="${COMP_WORDS[1]}"
    local PREV="${COMP_WORDS[COMP_CWORD-1]}"

    if [[ ${COMP_CWORD} -eq 1 && ${CURR} == -* ]]; then
        FLAGS="--help --version --make-config --all-formats -t -F"
        COMPREPLY=($(compgen -W "$FLAGS" -- ${CURR}))
        return 0
    elif [[ "${FIRST}" == --* ]]; then
        compopt +o default
        COMPREPLY=( )
        return 0
    elif [[ "${PREV}" == "-F" ]]; then
        Complete_Format
        return 0
    elif [[ "${CURR}" == -* ]]; then
        COMPREPLY=( $(compgen -W "-t -T -F" -- "${CURR}") )
        return 0
    fi
}

complete -o default -F _ufo ufo
