' com_xmlhttp.pb — XMLHTTP request simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL httpState AS LONG
    LOCAL requestID AS LONG
    LOCAL urlStr AS STRING
    LOCAL methodType AS LONG
    LOCAL statusCode AS LONG
    LOCAL responseSize AS LONG
    LOCAL responseData(500) AS LONG
    LOCAL responseLen AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL totalRequests AS LONG
    LOCAL successCount AS LONG
    LOCAL failCount AS LONG
    LOCAL responseByte AS LONG
    LOCAL iter AS LONG
    LOCAL maxRequests AS LONG
    LOCAL timeout AS LONG
    LOCAL readyState AS LONG
    LOCAL resultStr AS STRING

    maxRequests = 6

    PRINT "=== XMLHTTP Request Simulation ==="

    FOR totalRequests = 1 TO maxRequests
        requestID = totalRequests

        IF requestID = 1 THEN urlStr = "http://api.example.com/users"
        IF requestID = 2 THEN urlStr = "http://api.example.com/posts"
        IF requestID = 3 THEN urlStr = "http://api.example.com/comments"
        IF requestID = 4 THEN urlStr = "http://api.example.com/categories"
        IF requestID = 5 THEN urlStr = "http://api.example.com/tags"
        IF requestID = 6 THEN urlStr = "http://api.example.com/settings"

        httpState = 0
        readyState = 0

        readyState = 1
        httpState = 1

        readyState = 2
        httpState = 2

        readyState = 3

        IF requestID < 5 THEN
            statusCode = 200
            responseLen = 10 + requestID * 5
            FOR i = 0 TO responseLen - 1
                responseData(i) = 65 + i MOD 26
            NEXT i
            successCount = successCount + 1
        ELSE
            IF requestID = 5 THEN
                statusCode = 404
                responseLen = 0
                failCount = failCount + 1
            ELSE
                statusCode = 500
                responseLen = 0
                failCount = failCount + 1
            END IF
        END IF

        readyState = 4

        PRINT "  Request #" + STR$(requestID) + ": " + urlStr
        PRINT "    Status: " + STR$(statusCode) + " Size: " + STR$(responseLen) + " bytes"

        IF statusCode = 200 THEN
            resultStr = "    Data: "
            FOR i = 0 TO responseLen - 1
                resultStr = resultStr + CHR$(responseData(i))
            NEXT i
            PRINT resultStr
        END IF

        IF statusCode = 404 THEN
            PRINT "    Error: Not Found"
        END IF
        IF statusCode = 500 THEN
            PRINT "    Error: Server Error"
        END IF
    NEXT totalRequests

    PRINT "Success: " + STR$(successCount) + " Failed: " + STR$(failCount)
    PRINT "=== End XMLHTTP ==="
    FUNCTION = 0
END FUNCTION
