<!DOCTYPE html>
<html>
<head>
<script src="../resources/inspector-test.js"></script>
<script>
function loadSource(url, type) {
    let sourceElement = document.createElement("source");
    sourceElement.type = type;
    sourceElement.src = url;

    document.getElementById("video").appendChild(sourceElement);
}

function enterFullscreen(element) {
    document.addEventListener("keydown", (event) => {
        document.addEventListener("webkitfullscreenchange", (event) => {
            console.assert(document.webkitFullscreenElement === element);

            TestPage.dispatchEventToFrontend("TestPage-enteredFullscreen");
        }, {once: true});

        element.webkitRequestFullscreen();
    }, {once: true});

    if (window.testRunner) {
        // DumpRenderTree changes the firstResponder to the WebInspector window when it opens.
        // This refocuses the test page, ensuring it gets the event.
        if (window.testRunner.setMainFrameIsFirstResponder)
            window.testRunner.setMainFrameIsFirstResponder(true);

        eventSender.keyDown(" ");
    }
}

function exitFullscreen() {
    document.addEventListener("webkitfullscreenchange", (event) => {
        console.assert(!document.webkitFullscreenElement);

        TestPage.dispatchEventToFrontend("TestPage-exitedFullscreen");
    }, {once: true});

    document.webkitExitFullscreen();
}

function test()
{
    InspectorTest.debug();

    let suite = InspectorTest.createAsyncSuite("DOM.didFireEvent");

    let videoNode = null;

    function fullscreenTest(fullscreenElementId, resolve, reject) {
        InspectorTest.awaitEvent("TestPage-exitedFullscreen")
        .then(resolve, reject);

        InspectorTest.awaitEvent("TestPage-enteredFullscreen")
        .then((event) => {
            InspectorTest.log("Exiting fullscreen...");
            InspectorTest.evaluateInPage(`exitFullscreen()`).catch(reject);
        });

        let enabled = false;
        let listener = videoNode.addEventListener(WI.DOMNode.Event.DidFireEvent, (event) => {
            let {domEvent} = event.data;
            if (domEvent.eventName !== "webkitfullscreenchange")
                return;

            InspectorTest.pass(`Should receive a "webkitfullscreenchange" event.`);
            InspectorTest.expectGreaterThan(domEvent.timestamp, 0, "Event timestamp should be greater than 0.");
            InspectorTest.expectThat(domEvent.data, "Event should have data.");
            InspectorTest.expectNotEqual(domEvent.data.enabled, enabled, `Fullscreen should be ${!enabled}.`);
            InspectorTest.log("Target: " + event.target.displayName);
            if (domEvent.originator)
                InspectorTest.log("Originator: " + domEvent.originator.displayName);

            enabled = domEvent.data.enabled;
            if (!enabled)
                videoNode.removeEventListener(WI.DOMNode.Event.DidFireEvent, listener);
        });

        InspectorTest.log(`Entering fullscreen on #${fullscreenElementId}...`);
        InspectorTest.evaluateInPage(`enterFullscreen(document.getElementById("${fullscreenElementId}"))`).catch(reject);
    }

    suite.addTestCase({
        name: "DOM.didFireEvent.Basic",
        description: "Check that HTMLMediaElement events work.",
        test(resolve, reject) {
            const file = "white.mp4";

            let listener = videoNode.addEventListener(WI.DOMNode.Event.DidFireEvent, (event) => {
                let {domEvent} = event.data;
                if (domEvent.eventName !== "loadstart")
                    return;

                InspectorTest.pass(`Should receive a "loadstart" event.`)
                InspectorTest.expectGreaterThan(domEvent.timestamp, 0, "Event timestamp should be greater than 0.");

                videoNode.removeEventListener(WI.DOMNode.Event.DidFireEvent, listener);
                resolve();
            });

            InspectorTest.log(`Adding video source "resources/${file}"...`);
            InspectorTest.evaluateInPage(`loadSource("resources/${file}", "video/mp4")`);
        }
    });

    suite.addTestCase({
        name: "DOM.didFireEvent.Fullscreen",
        description: "Check that fullscreen events work.",
        test(resolve, reject) {
            fullscreenTest("video", resolve, reject);
        }
    });

    suite.addTestCase({
        name: "DOM.didFireEvent.Inherited",
        description: "Check that inherited events work.",
        test(resolve, reject) {
            fullscreenTest("container", resolve, reject);
        }
    });

    WI.domManager.requestDocument((documentNode) => {
        documentNode.querySelector("#video", (videoNodeId) => {
            videoNode = WI.domManager.nodeForId(videoNodeId);
            if (videoNode)
                suite.runTestCasesAndFinish();
            else {
                InspectorTest.fail(`DOM node for "#video" not found.`);
                InspectorTest.completeTest();
            }
        });
    });
}
</script>
</head>
<body onload="runTest()">
    <p>Tests that listeners registered by InspectorDOMAgent::addEventListenersToNode are working.</p>
    <div id="container">
        <video id="video" muted autoplay></video>
    </div>
</body>
</html>
