<!DOCTYPE html>
<html>
<head>
    <script src="../../resources/js-test-pre.js"></script>
    <script src="../../media/media-file.js"></script>
    <script src="../../media/utilities.js"></script>
    <script src="../../resources/platform-helper.js"></script>
</head>
<body>
<script>
    description("Test the behavior of 2d canvas createPattern as a video is loaded");

    var buffer;
    var expectedResults = [
        // Each entry is formatted as [x, y, r, g, b].
        [40, 165, 200, 200, 0], // Represents yellow north west tile.
        [355, 165, 200, 200, 0], // Represents yellow north east tile.
        [40, 403, 200, 200, 0], // Represents yellow south west tile.
        [355, 403, 200, 200, 0], // Represents yellow south east tile.

        [56, 165, 57, 202, 203], // Represents blue/cyan north west tile.
        [371, 165, 57, 202, 203], // Represents blue/cyan north east tile.
        [56, 403, 57, 202, 203], // Represents blue/cyan south west tile.
        [371, 403, 57, 202, 203], // Represents blue/cyan south east tile.

        [73, 165, 53, 203, 9], // Represents green north west tile.
        [388, 165, 53, 203, 9], // Represents green north east tile.
        [73, 403, 53, 203, 9], // Represents green south west tile.
        [388, 403, 53, 203, 9], // Represents green south east tile.
    ];

    var canvases = document.createElement("div");
    document.body.appendChild(canvases);

    var video = document.createElement("video");

    shouldBeNull("document.createElement('canvas').getContext('2d').createPattern(video, 'repeat')");

    waitForVideoFrame(video, firstframe);
    video.src = findMediaFile("video", "../../media/content/test");


    function checkPixels(context, x, y, r, g, b, tolerance)
    {
        buffer = context.getImageData(x, y, 1, 1).data;
        shouldBeCloseTo("buffer[0]", r, tolerance);
        shouldBeCloseTo("buffer[1]", g, tolerance);
        shouldBeCloseTo("buffer[2]", b, tolerance);
    }

    function drawImageToCanvasAndCheckPixels()
    {
        var canvas = document.createElement("canvas");
        canvas.width = 2.5 * video.videoWidth;
        canvas.height = 2.5 * video.videoHeight;
        var context = canvas.getContext("2d");
        document.body.appendChild(canvas);

        context.fillStyle = context.createPattern(video, "repeat");
        context.fillRect(0, 0, canvas.width, canvas.height);

        expectedResults.forEach(function(element) {
            checkPixels(context, element[0], element[1], element[2], element[3], element[4], videoCanvasPixelComparisonTolerance());
        });
    }

    async function firstframe()
    {
        drawImageToCanvasAndCheckPixels();

        video.currentTime = 0.996;
        await once(video, 'seeked');

        drawImageToCanvasAndCheckPixels();

        finishJSTest();
    }

    window.jsTestIsAsync = true;
</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
