<head>
<script src="/resources/js-test-pre.js"></script>
<script src="/resources/notifications-test-pre.js"></script>
<script>

function failTheTest(msg)
{
    testFailed(msg);
    if (testRunner)
        testRunner.notifyDone();
}

if (window.testRunner) {
    testRunner.waitUntilDone();
    testRunner.grantWebNotificationPermission(testURL);
    setTimeout("failTheTest('timed out')", 15000);
}

description("This tests that a notification shown by a service worker registration in a document can be clicked and closed, with those actions being observable by the service worker");

shouldBeEqualToString("Notification.permission", "granted");

var threwDataCloneError = false;

async function registerServiceWorker() {
    var registration = await navigator.serviceWorker.register('resources/shownotification-worker.js');

    if (!registration)
        return testFailed("No registration");

    if (registration.active) {
        registration.active.postMessage("Start");
        return;
    }

    var installingWorker = registration.installing;
    if (!installingWorker)
        failTheTest("No active *or* installing worker");

    installingWorker.addEventListener("statechange", async () => {
        if (installingWorker.state === "activated") {
            try {
                await registration.showNotification("Invalid notification", { data: function() { } });
            } catch (error) {
                threwDataCloneError = error.name == 'DataCloneError';
            }
            shouldBeTrue('threwDataCloneError');

            await registration.showNotification("This is a notification", { body: "body", tag: "tag", data: "foobar" });
            if (window.testRunner)
                testRunner.simulateWebNotificationClickForServiceWorkerNotifications();
        }
    });
}

var gotClicked = false;
var gotClosed = false;

navigator.serviceWorker.addEventListener('message', async event => {
    if (event.data == "showFailed") {
        failTheTest("Unexpectedly received the failed-to-show message");
    } else if (event.data == "clicked|data:foobar") {
        shouldBeFalse("gotClicked");
        shouldBeFalse("gotClosed");
        gotClicked = true;
    } else if (event.data == "closed") {
        shouldBeTrue("gotClicked")
        shouldBeFalse("gotClosed")
        gotClosed = true;
    } else {
        testFailed("Message received: " + event.data);
    }

    if (gotClosed) {
        testPassed("Close has been observed");
        if (window.testRunner)
            testRunner.notifyDone();
    }
});

</script>
</head>
<body onload="registerServiceWorker()">
</body>
