# shellcheck shell=dash

___x_cmd_cosmo___ls(){
    [ "$#" -gt 0 ] ||   set -- --all
    local op="$1"; shift
    case "$op" in
        -h|--help)      x help -m cosmo --ls; return  ;;
        --all)          ___x_cmd_cosmo___ls_all       ;;
        --local)        ___x_cmd_cosmo___ls_local     ;;
    esac
}

___x_cmd_cosmo___ls_all(){
    if ___x_cmd_is_stdout2tty; then
        ___x_cmd_cosmo___ls_app
    else
        ___x_cmd_cosmo___ls_raw
    fi
}

___x_cmd_cosmo___ls_raw(){
    local x_
    ___x_cmd_cosmo___binlist_
    x_="${x_#"$___X_CMD_UNSEENCHAR_NEWLINE"}"
    x_="${x_%"$___X_CMD_UNSEENCHAR_NEWLINE"}"
    printf "%s\n" "${x_}"
}

___x_cmd_cosmo___ls_app(){

    cosmo:info "Navigate among all availabe cosmo binaries. You can select one to continue."

    local x_=""
    ___X_CMD_PICK_SHBIN_CODE="xrc cosmo" \
        ___x_cmd storeread_  ___x_cmd pick --col 8 ___x_cmd_cosmo___ls_raw
    local bin="$x_"

    [ -n "$bin" ] || return $?

    cosmo:info "FYI -- You can directly run as follow -> x cosmo $bin [argument...]"
    # TODO: In the future: x cosmo $bin --tldr
    cosmo:info "FYI -- Or you can install the bin in local directory -> x cosmo --install $bin [target directory]"

    local id=
    ___x_cmd ui select id  "Next:" \
        "x cosmo use $bin           # Install the tool into the current user's global environment"  \
        "x cosmo $bin --help        # show help"                                                    \
        "x cosmo --install $bin     # install $bin into the directory in PATH"                      \
        "EXIT"                                                                                      || return

    case "$id" in
        1)      ___x_cmd cosmo use "$bin"          ;;
        2)      ___x_cmd cosmo "$bin" --help       ;;
        3)      ___x_cmd cosmo --install "$bin"    ;;
        *)      return ;;
    esac
}

___x_cmd_cosmo___ll(){
    ___x_cmd_cosmo___ls_raw
}

___x_cmd_cosmo___ls_local(){
    if ___x_cmd_is_stdout2tty; then
        ___x_cmd_cosmo___ls_local_app
    else
        ___x_cmd_cosmo___ls_local_raw
    fi
}

___x_cmd_cosmo___ls_local_raw(){
    ___x_cmd fsiter "$___X_CMD_COSMO_BIN_PATH/$___X_CMD_COSMO_VERSION"
}

___x_cmd_cosmo___ls_local_app(){
    ___x_cmd pick --col 8 ___x_cmd_cosmo___ls_local_raw
}
