<!--
  Any copyright is dedicated to the Public Domain.
  http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function ok(exp, msg) {
  if (!exp) {
    throw(msg);
  }
}

function is(actual, expected, msg) {
  if (actual !== expected) {
    throw('got "' + actual + '", but expected "' + expected + '" - ' + msg);
  }
}

function fail(err) {
  window.dispatchEvent(new Event("cached-failure", { bubbles: true, detail: err }));
}

function getUncontrolledClients(sw) {
  return new Promise(function(resolve, reject) {
    navigator.serviceWorker.addEventListener('message', function onMsg(evt) {
      if (evt.data.type === 'CLIENTS') {
        navigator.serviceWorker.removeEventListener('message', onMsg);
        resolve(evt.data.detail);
      }
    });
    sw.postMessage({ type: 'GET_UNCONTROLLED_CLIENTS' })
  });
}

addEventListener('load', function(event) {
  if (!navigator.serviceWorker.controller) {
    return fail(window.location.href + ' is not controlled!');
  }

  getUncontrolledClients(navigator.serviceWorker.controller)
    .then(function(clientList) {
      is(clientList.length, 1, 'should only have one client');
      is(clientList[0].url, window.location.href,
         'client url should match current window');
      is(clientList[0].frameType, 'top-level',
         'client should be a top-level window');
      window.dispatchEvent(new Event('cached-load', { bubbles: true }));
    })
    .catch(function(err) {
      fail(err);
    });
});
</script>
</body>
</html>
