<!DOCTYPE HTML>
<html>
<head>
<script src="../../../../js-test-resources/js-test-pre.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script>
description("Test WebSocket deflate-frame extension.");

window.jsTestIsAsync = true;

var closeEvent;
var ws;
var messageIndex;

var queries = [
    "max_window_bits=8",
    "no_context_takeover",
    "max_window_bits=8&no_context_takeover"
];

// The first message consists of a lot of 'b' and a few 'a' at the head and
// the tail, while the second one consists of 'a'.
var firstMessage = '';
var secondMessage = '';
for (var i = 0; i < 16; ++i) {
    firstMessage += 'a';
    secondMessage += 'a';
}
for (var i = 0; i < 1024; ++i) {
    firstMessage += 'b';
    secondMessage += 'a';
}
for (var i = 0; i < 16; ++i) {
    firstMessage += 'a';
    secondMessage += 'a';
}

let testResult;
function doTest(queryIndex)
{
    var query = queries[queryIndex];
    debug("Testing query: \"" + query + "\"");

    var url = "ws://localhost:8880/websocket/tests/hybi/deflate-frame?" + query;
    ws = new WebSocket(url);
    messageIndex = 0;

    ws.onopen = function(event)
    {
        const isUsingLegacyExtension = ws.extensions.search('x-webkit-deflate-frame') != -1;
        if (isUsingLegacyExtension) {
            testResult = true;
            parameters = query.split('&');
            for (var i = 0; i < parameters.length; ++i)
                testResult = testResult && (ws.extensions.search(parameters[i]) != -1);
        } else
            testResult = ws.extensions.search('permessage-deflate') != -1;
        shouldBeTrue('testResult');
        ws.send(firstMessage);
    };

    ws.onmessage = function(event)
    {
        if (messageIndex === 0) {
            shouldBe("event.data", "firstMessage");
            messageIndex += 1
            ws.send(secondMessage);
        } else {
            shouldBe("event.data", "secondMessage");
            ws.close();
        }
    };

    ws.onclose = function(event)
    {
        debug("onclose() was called.");
        closeEvent = event;
        shouldBeTrue("closeEvent.wasClean");
        if (queryIndex === queries.length - 1)
            finishJSTest();
        else
            doTest(queryIndex + 1);
    };
}

doTest(0);

</script>
<script src="../../../../js-test-resources/js-test-post.js"></script>
</body>
</html>
