<!-- webkit-test-runner [ UsesBackForwardCache=true ] -->
<!DOCTYPE html>
<html>
<body>
<script src="resources/sw-test-pre.js"></script>
<script>
log("* Tests that a client is removed from the list of service worker clients while it is in the page cache");
log("");

let topClientIdentifier = null;
let windowClientIdentifier = null;
let dedicatedWorker = null;
let tries = 0;

function containsBothClients(clientIdentifiers)
{
    return clientIdentifiers.includes(topClientIdentifier) && clientIdentifiers.includes(windowClientIdentifier);
}

function containsOnlyTopClient(clientIdentifiers)
{
    return clientIdentifiers.includes(topClientIdentifier) && !clientIdentifiers.includes(windowClientIdentifier);
}

navigator.serviceWorker.addEventListener("message", function(event) {
  if (step == "AllClientsInitiallyActive") {
    if (!containsBothClients(event.data.ids) && event.data.workersCount !== 2) {
      if (++tries > 20) {
          log("FAIL: Wrong initial number of clients");
          finishSWTest();
          return;
      }
      worker.postMessage("getClientIds");
      return;
    }
    log("PASS: service worker has initially 2 window clients");
    log("PASS: service worker has initially 2 worker clients");

    otherWindow.addEventListener("pagehide", function(event) {
       if (!event.persisted) {
         log("FAIL: page failed to enter page cache");
         finishSWTest();
         return;
       }
       log("PASS: page is about to enter page cache");

       setTimeout(function() {
         step = "OnlyOneClientRemainsActive"
         worker.postMessage("getClientIds");
       }, 0);
    });

    otherWindow.location.href = "about:blank";
    return;
  }

  if (step == "OnlyOneClientRemainsActive") {
    if (!containsOnlyTopClient(event.data.ids) && event.data.workersCount !== 1) {
      log("FAIL: Wrong number of clients after one client entered page cache");
      finishSWTest();
    }

    log("PASS: service worker has only 1 window client after 1 entered page cache");
    log("PASS: service worker has only 1 worker client after 1 entered page cache");
    finishSWTest();
  }
});

navigator.serviceWorker.register("resources/getClientIds-worker.js", { }).then(async (registration) => {
    if (!window.internals)
        return;
    topClientIdentifier = internals.serviceWorkerClientInternalIdentifier(document);

    worker = registration.installing;

    dedicatedWorker = new Worker("other_resources/dummy.js");

    otherWindow = open("other_resources/test.html");
    await new Promise(resolve => otherWindow.onload = resolve);
    windowClientIdentifier = internals.serviceWorkerClientInternalIdentifier(otherWindow.document);
    step = "AllClientsInitiallyActive"
    worker.postMessage("getClientIds");
});
</script>
</body>
</html>
