<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test-pre.js"></script>
</head>
<body>
    <img src="">
    <script>
        function drawFrame(image, frame) {
            return new Promise((resolve) => {
                // Force layout and display so the image frame starts decoding
                document.body.offsetHeight;
                testRunner.display();

                image.addEventListener("webkitImageFrameReady", function listener() {
                    debug("Image frame: " + frame + " was displayed.");
                    image.removeEventListener("webkitImageFrameReady", listener, true);
                    resolve(frame + 1);
                }, true);
            });
        }

        function drawImage(image, frameCount) {
            let promise = drawFrame(image, 0);
            for (let i = 1; i < frameCount; ++i) {
                promise = promise.then((frame) => {
                    return drawFrame(image, frame);
                });
            }
            return promise;
        }

        function loadAndDrawImage(image, src, frameCount) {
            return new Promise((resolve) => {
                image.onload = (() => {
                    debug("Image was loaded successfully.");
                    drawImage(image, frameCount).then(resolve);
                });
                image.src = src;
            });
        }

        (function() {
            window.jsTestIsAsync = true;

            if (window.internals) {
                internals.clearMemoryCache();
                internals.settings.setWebkitImageReadyEventEnabled(true);
                internals.settings.setAnimatedImageAsyncDecodingEnabled(true);
            }

            description("Verify HEICS image can animate.");

            let image = document.querySelector("img");

            loadAndDrawImage(image, "resources/sticker.heics", 3).then(() => {
                debug("The HEICS Image was loaded and three frames of it were displayed successfully.");
                finishJSTest();
            });
        })();
    </script>
    <script src="../../resources/js-test-post.js"></script>
</body>
</html>
