<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 notificationclick handler can open a window");

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

async function registerServiceWorker() {
    var registration = await navigator.serviceWorker.register('resources/shownotification-openwindow-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", () => {
        if (installingWorker.state === "activated") {
            installingWorker.postMessage("tryshow|title|body|tag|foobar");
        }
    });
}

var gotClicked = false;
var gotClosed = false;
var gotNewClient = false;
var gotAboutBlankFail = false;
var gotUserGestureFail = false;
var gotSuccessfulNullClient = false;

navigator.serviceWorker.addEventListener('message', event => {
    if (event.data == "showFailed") {
        failTheTest("Unexpectedly received the failed-to-show message");
    } else if (event.data == "shown") {
        if (testRunner)
            testRunner.simulateWebNotificationClickForServiceWorkerNotifications();
    } 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 if (event.data == "gotNewClient") {
        gotNewClient = true;
    } else if (event.data == "gotAboutBlankFail") {
        gotAboutBlankFail = true;
    } else if (event.data == "gotUserGestureFail") {
        gotUserGestureFail = true;
    } else if (event.data = "gotSuccessfulNullClient") {
        gotSuccessfulNullClient = true;
    } else {
        testFailed("Message received: " + event.data);
    }
    
    if (gotNewClient) {
        shouldBeTrue("gotAboutBlankFail");
        shouldBeTrue("gotUserGestureFail");
        shouldBeTrue("gotSuccessfulNullClient");
        testPassed("New client has been observed");
        if (window.testRunner)
            testRunner.notifyDone();
    }
});

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