# shellcheck shell=sh
# shellcheck disable=SC2039,3043,2046

# Section: HTTP header & body & request
___x_cmd_cf_curl(){
    local op="$1"
    local _api_url="$2"
    shift 2
    local content_type="${cf_content_type}"

    case "$op" in
        get)
            if [ -n "$NO_CACHE" ]; then
                x api cf "$op" "$_api_url" $(eval "printf '%s ' $(x curl gencode $(___x_cmd_cf_curl___use_query_data "$@"))")
            else
                x ccmd 10s --               eval "x api cf get \"$_api_url\" $(eval "printf '%s ' $(x curl gencode $(___x_cmd_cf_curl___use_query_data "$@"))")"
            fi
            ___x_cmd_cf_http_error  eval "x api cf get \"$_api_url\" $(eval "printf '%s ' $(x curl gencode $(___x_cmd_cf_curl___use_query_data "$@"))")"
            ;;
        post|put|patch|delete)
            x api cf "$op" "$_api_url" "$(x curl gencode "$@")" "${_file_path:+"-T \"${_file_path}\""}"
            ___x_cmd_cf_http_error
            ;;
    esac
}

___x_cmd_cf_curl___use_query_data(){
    [ $# -gt 0 ] || return
    printf "%s " "-G"
    local name=""
    for name in "$@"; do
        printf "%s " "$name=="
    done
}

___x_cmd_cf_resp_header(){
   command cat "$___X_CMD_API_TMP/.____x_cmd_cf_curl_header"
}

___x_cmd_cf_resp_code(){
    ___x_cmd_cf_resp_header | {
        command awk '{
            if ($1 ~ "HTTP/(1.*|2)$" && $3 != "Connection" && $4 != "established") {
                print $2;
                exit(0)
            }
        }'
    }
}

___x_cmd_cf_http_error(){
    if [ "$___X_CMD_CCMD_AGE" -ne -1 ]; then
        cf:debug "Cache info"
        return 0
    fi
    local http_resp_code
    http_resp_code=$(___x_cmd_cf_resp_code)
    if [ -n "$http_resp_code" ] && [ "$http_resp_code" -ge 200 ] && [ "$http_resp_code" -le 303 ]; then
        return 0
    else
        [ $# -lt 0 ] || {
            cf:debug "Cache Clear"
            x ccmd invalidate "$@"
        }
        cf:error "HTTP Code is $http_resp_code"
        return 1
    fi
}
# EndSection

# Section: Default param util
alias ___x_cmd_cf_param_default='
    local account_id=""
    ___x_cmd_cf_param_default_parse  || return
'

___x_cmd_cf_param_default_parse(){
    account_id="$(___x_cmd cf --cfg get account_id 2>/dev/null)"
    [ -n "$account_id" ] || {
        cf:error "Get cf failed, please use 'x cf --cfg set account_id' to set up the configuration."
        return 1
    }

    # [ -n "$zone_id" ] || zone_id="$(x cf --cfg get zone_id 2>/dev/null)"
}
