
# shellcheck shell=dash

___x_cmd_hotkey_fzf(){
    local op="$1";
    case "$op" in
        --bind)     shift; ___x_cmd_hotkey_fzf___bind   "$@" ;;
        -h|--help)  ___x_cmd help -m hotkey fzf;            return ;;
        *)          ___x_cmd help -m hotkey fzf >&2;        return 64 ;;
    esac
}

___x_cmd_hotkey_fzf___bind(){
    local FZF_CTRL_T_COMMAND=""
    local FZF_CTRL_R_COMMAND=""
    local FZF_ALT_C_COMMAND=""

    while [ "$#" -gt 0 ] ; do
        case "$1" in
            --ctrl-r)  shift; unset FZF_CTRL_R_COMMAND ;;
            --ctrl-t)  shift; unset FZF_CTRL_T_COMMAND ;;
            --alt-c)   shift; unset FZF_ALT_C_COMMAND ;;
            *) break ;;
        esac
    done

    ___x_cmd_hotkey___widget_supported fzf-history || return 1

    local dir="$___X_CMD_ROOT_TMP/hotkey/fzf"
    local fp=""
    if [ -n "$ZSH_VERSION" ]; then
        fp="$dir/keybind.zsh"
    else
        fp="$dir/keybind.bash"
    fi

    ___x_cmd_hotkey_fzf___check || return $?
    [ -f "$fp" ] || N=hotkey M="Not found key-bindings file -> $fp" log:ret:1
    . "$fp"
}

___x_cmd_hotkey_fzf___check(){
    ___x_cmd_hascmd fzf || ___x_cmd env use fzf || {
        hotkey:error "Required fzf command not found, please install fzf or set env FZF_PATH to the executable path"
        return 1
    }

    local dir="$___X_CMD_ROOT_TMP/hotkey/fzf"
    ___x_cmd mkdirp "$dir" || return $?
    ___x_cmd_cmds fzf --bash > "$dir/keybind.bash"
    ___x_cmd_cmds fzf --zsh | \
        ___x_cmd_cmds awk '{ print $0; }($0 ~ "### end: key-bindings.zsh ###"){ exit(0); }' > "$dir/keybind.zsh"
}
