# shellcheck shell=bash disable=2034

# TODO: Must has a better way to do this. Should be more like native ls complete
___x_cmd_hub__advise(){
    local X_help_cmd='___x_cmd_hub___help _advise'
    help:arg-null:parse

    case "$1" in
        lsfile) shift; ___x_cmd_hub__advise_lsfile "$@" ;;
        *)      hub:error "Unknown advise subcmd: $1" ;;
    esac
}

___x_cmd_hub__advise_lsfile(){
    case "$1" in
        --with-prefix) ___x_cmd_hub__advise___lsfile_with_prefix "$cur" ;;
        *)             ___x_cmd_hub__advise___lsfile "$cur" ;;
    esac
}

# x me:<tab>
# x hub file cat o-plrom:<tab>
___x_cmd_hub__advise___lsfile(){
    local cur="$1";   local dir="${cur%"${cur##*/}"*}";   local l=
    [ -n "$dir" ] || dir="${cur%"${cur#*:}"*}"

    [ -n "$dir" ] || {
        ___x_cmd ccmd 1m -- ___x_cmd_hub__advise_cache_org_ls_name | while read -r l; do
            printf "%s\n" "${l}:"
        done
    }

    ___x_cmd ccmd 1m -- ___x_cmd_hub__advise_cache_file_ls "$dir" | while read -r l; do
        printf "%s\n" "${dir}${l}"
    done
}

___x_cmd_hub__advise___lsfile_with_prefix(){
    case "$1" in
        *:*)    ;;
        *)      printf "%s\n" "me:";    return ;;
    esac

    local cur="${1}";   local dir="${cur%"${cur##*/}"*}";   local l=
    [ -n "$dir" ] || dir="${cur%"${cur#*:}"*}"

    ___x_cmd ccmd 1m -- ___x_cmd_hub__advise_cache_file_ls "$dir" | while read -r l; do
        printf "%s\n" "${dir}${l}"
    done
}

# Prevent sending requests for every completion when call fails
___x_cmd_hub__advise_cache_file_ls(){
    ___x_cmd hub file ls "$@" || true
}

___x_cmd_hub__advise_cache_org_ls_name(){
    ___x_cmd hub org _ls_name "$@" || true
}

