<!DOCTYPE html>
<html>
    <head>
        <script src=../../media-resources/video-test.js></script>
        <script>
            if (window.testRunner) {
                testRunner.dumpAsText();
                testRunner.waitUntilDone();
            }

            const redColor = new Uint8ClampedArray([255, 0, 0, 255]);
            const greenColor = new Uint8ClampedArray([0, 255, 0, 255]);

            function arraysAreApproximatelyEqual(array, expected, tolerance) {
                for (var index in array) {
                    if (Math.abs(array[index] - expected[index]) <= tolerance)
                        continue;
                    return false;
                }
                return true;
            }


            async function shouldBecomeColor(color) {
                return new Promise((resolve, reject) => {
                    let interval = setInterval(() => {
                        var canvas = document.createElement('canvas');
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        let context = canvas.getContext('2d');
                        context.drawImage(video, 0, 0, canvas.width, canvas.height);
                        let foundColor = context.getImageData(canvas.width / 2, canvas.height / 2, 1, 1).data;
                        document.getElementById("debugLog").innerHTML += "Current color: " + foundColor + "<br>";
                        if (arraysAreApproximatelyEqual(foundColor, color, 70)) {
                            clearInterval(interval);
                            logResult(true, `video became equal to ${ color }`);
                            resolve();
                        }
                    }, 1000);
                });
            }

            async function start() {
                if (!window.internals) {
                    consoleWrite('This test requires WebKit Internals');
                    endTest();
                    return;
                }

                video = document.getElementById('video');

                run('internals.setOverridePreferredDynamicRangeMode(video, "Standard")');
                run('video.src = "../resources/hls/hdr.m3u8"');

                await shouldBecomeColor(redColor);

                run('internals.setOverridePreferredDynamicRangeMode(video, "DolbyVisionPQ")');

                await shouldBecomeColor(greenColor);

                run('internals.setOverridePreferredDynamicRangeMode(video, "Standard")');

                await shouldBecomeColor(redColor);

                document.getElementById("debugLog").remove();
                endTest();
            }
        </script>
    </head>
    <body onload="start()">
        <video id="video" autoplay muted></video>
        <div id=debugLog>Debug log:<br></div>
    </body>
</html>
