# shellcheck shell=dash disable=SC2154,SC2034

___x_cmd_shodan_entitydb_ls(){
    local X_help_cmd='x help -m shodan entitydb ls';   help:arg:parse
    if ! ___x_cmd_shodan_is_interactive_env; then
        ___x_cmd_shodan_entitydb_ls___raw
        return 0
    fi


    local ___X_CMD_CSV_APP_DATA_CURROW=

    ___x_cmd_shodan_entitydb_ls___raw | ___x_cmd_shodan_entitydb_ls___parse_json2csv |  x csv --app --return line
    local eid=${___X_CMD_CSV_APP_DATA_CURROW%%,*}

    [ -n "$eid" ] || return

    local name="${___X_CMD_CSV_APP_DATA_CURROW#*,}"
    name="${name%%,*}"

    local id=
    x ui select id \
        "Next move for [ entity=$name]"      \
        "Open on website"                    \
        "Exit"

    case "$id" in
        1)      x open "https://entitydb.shodan.io/entities/$eid" ;;
        2)      return
    esac

    # "View the entity data in terminal"  \
    # 2)      ___x_cmd_shodan_entitydb_id "$eid" | x j2y ;;  # In the future, we will use a interactive json.
}

___x_cmd_shodan_entitydb_ls___raw(){
    x ccmd "$___X_CMD_SHODAN_ENTITYDB_TIMELIMIT" 2>/dev/null -- \
        x curl  --fail-with-body  -sS \
        "https://entitydb.shodan.io/api/entities" \
        || N=shodan M="Fail for name=${name}" log:ret:1
}

___x_cmd_shodan_entitydb_ls___parse_json2csv(){
    ___x_cmd jo .entities | x jo 2c .id .tickers .entity_name  |\
        ___x_cmd cawk -m csv -f "$___X_CMD_ROOT_MOD/csv/lib/awk/csva.awk" \
                             -f  "$___X_CMD_ROOT_MOD/shodan/lib/entitydb/entitydb_ls.awk"
}

