<!DOCTYPE html>
<meta charset="utf-8"/>
<meta name="timeout" content="long">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/cookies/resources/cookie-helper.sub.js"></script>
<!-- We're appending an <iframe> to the document's body, so execute tests after we have a body -->
<body>
<script>
  // This test creates an iframe with postToParent.py on the specified origin,
  // which sends a postMessage event with the cookies it received back to the
  // parent (i.e., here). Upon receiving the message, the test verifies that the
  // correct cookies were sent to the iframe, and posts a message back to the
  // iframe telling it to reload itself. Upon reload, the iframe sends a
  // postMessage event back to the test with the cookies it received, which are
  // again verified.
  function create_test(origin, target, expectedStatus, expectedDomStatus, title) {
    promise_test(t => {
      var value = "" + Math.random();
      return resetSameSiteCookies(origin, value)
        .then(_ => {
          return new Promise((resolve, reject) => {
            var iframe = document.createElement("iframe");
            iframe.onerror = _ => reject("IFrame could not be loaded.");

            var reloaded = false;
            var msgHandler = e => {
              try {
                verifySameSiteCookieState(expectedStatus, value, e.data, expectedDomStatus);
              } catch (e) {
                reject(e);
              }

              if (reloaded) {
                window.removeEventListener("message", msgHandler);
                document.body.removeChild(iframe);
                resolve("IFrame received the cookie.");
              } else {
                reloaded = true;
                e.source.postMessage("reload", "*");
              }
            };
            window.addEventListener("message", msgHandler);

            iframe.src = target + "/cookies/resources/postToParent.py";
            document.body.appendChild(iframe);
          });
        });
    }, title);
  }

  create_test(SECURE_ORIGIN, SECURE_ORIGIN, SameSiteStatus.STRICT, DomSameSiteStatus.SAME_SITE, "Reloaded same-host fetches are strictly same-site");
  create_test(SECURE_SUBDOMAIN_ORIGIN, SECURE_SUBDOMAIN_ORIGIN, SameSiteStatus.STRICT, DomSameSiteStatus.SAME_SITE, "Reloaded subdomain fetches are strictly same-site");
  create_test(SECURE_CROSS_SITE_ORIGIN, SECURE_CROSS_SITE_ORIGIN, SameSiteStatus.CROSS_SITE, DomSameSiteStatus.CROSS_SITE, "Reloaded cross-site fetches are cross-site");
</script>
