<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="resources/webgl_test_files/resources/js-test-style.css"/>
<script src="resources/webgl_test_files/js/js-test-pre.js"></script>
<script src="resources/webgl_test_files/js/webgl-test-utils.js"></script>
</head>
<body onload="test()">
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
description("Test that a context can be lost multiple times.");

var wtu = WebGLTestUtils;
var gl;

async function waitForWebGLContextLostAndRestore(canvas)
{
    return new Promise((resolve, reject) => {
        const rejectID = setTimeout(reject, 2000);
        function handleContextLoss(event) {
            console.log("got here 1");
            clearTimeout(rejectID);
            event.preventDefault();
            console.log("got here 2");

            resolve();
        }
        canvas.addEventListener("webglcontextlost", handleContextLoss, { once: true });
    });
}

async function waitForWebGLContextRestored(canvas)
{
    return new Promise((resolve, reject) => {
        setTimeout(reject, 2000);
        canvas.addEventListener("webglcontextrestored", resolve, { once: true });
    });
}

async function runTest()
{
    if (!window.internals) {
        testFailed("Needs internals.");
        return;
    }
    const canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    gl = wtu.create3DContext(canvas);

    for (let i = 0; i < 7; ++i) {
        const webglcontextlostandrestore = waitForWebGLContextLostAndRestore(canvas);
        const webglcontextrestored = waitForWebGLContextRestored(canvas);

        internals.simulateEventForWebGLContext("GPUStatusFailure", gl);
        gl.clear(gl.COLOR_BUFFER_BIT);

        try {
            await webglcontextlostandrestore;
            testPassed(`Got webglcontextlost iteration:${i}`);
        } catch (e) {
            testFailed(`Timed out waiting webglcontextlost iteration:${i}` + e);
            return;
        }
        shouldBeTrue("gl.isContextLost()");
        shouldBe("gl.getError()", "gl.CONTEXT_LOST_WEBGL");
        shouldBe("gl.getError()", "gl.NO_ERROR");
        try {
            await webglcontextrestored;
            testPassed(`Got webglcontextrestored iteration:${i}`);
        } catch (e) {
            testFailed(`Timed out waiting webglcontextrestored iteration:${i}`);
            return;
        }
        shouldBeFalse("gl.isContextLost()");
        shouldBe("gl.getError()", "gl.NO_ERROR");
    }
}

async function test()
{
    await runTest();
    finishTest();
}

</script>
</body>
</html>
