<!DOCTYPE html>
<title>Service Worker: Clients.matchAll</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.sub.js"></script>
<script>
var scope = 'resources/clients-frame-freeze.html';
var windows = [];
var expected_window_1 =
    {visibilityState: 'visible', focused: false, lifecycleState: "frozen", url: new URL(scope + '#1', location).toString(), type: 'window', frameType: 'top-level'};
var expected_window_2 =
    {visibilityState: 'visible', focused: false, lifecycleState: "active", url: new URL(scope + '#2', location).toString(), type: 'window', frameType: 'top-level'};
function with_window(url, name) {
  return new Promise(function(resolve) {
    var child = window.open(url, name);
    window.onmessage = () => {resolve(child)};
  });
}

promise_test(function(t) {
    return service_worker_unregister_and_register(
        t, 'resources/clients-matchall-worker.js', scope)
      .then(function(registration) {
          t.add_cleanup(function() {
              return service_worker_unregister(t, scope);
            });

          return wait_for_state(t, registration.installing, 'activated');
        })
      .then(function() { return with_window(scope + '#1', 'Child 1'); })
      .then(function(window1) {
          windows.push(window1);
          return with_window(scope + '#2', 'Child 2');
        })
      .then(function(window2) {
          windows.push(window2);
          return new Promise(function(resolve) {
              window.onmessage = resolve;
              windows[0].postMessage('freeze');
            });
        })
      .then(function() {
          var channel = new MessageChannel();

          return new Promise(function(resolve) {
              channel.port1.onmessage = resolve;
              windows[1].navigator.serviceWorker.controller.postMessage(
                  {port:channel.port2, includeLifecycleState: true}, [channel.port2]);
            });
        })
      .then(function(e) {
          assert_equals(e.data.length, 2);
          // No specific order is required, so support inversion.
          if (e.data[0][3] == new URL(scope + '#2', location)) {
            assert_object_equals(e.data[0], expected_window_2);
            assert_object_equals(e.data[1], expected_window_1);
          } else {
            assert_object_equals(e.data[0], expected_window_1);
            assert_object_equals(e.data[1], expected_window_2);
          }
      });
}, 'Test Clients.matchAll()');

</script>
