<!DOCTYPE HTML>
<html>
<head>
  <title>Test for postMessages cloning/transferring objects</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
  <script src="common_postMessages.js"></script>
</head>

<body>
<input id="fileList" type="file"></input>
<script type="application/javascript">

// PostMessage to the same window.
tests.push(function test_windowToWindow() {
  info("Testing window to window");
  var resolve;

  function resolvePromise(data) {
    if (!resolve) {
      ok(false, "Unexpected message!");
      return;
    }

    let tmp = resolve;
    resolve = null;
    tmp(data);
  }

  onmessage = function(e) {
    resolvePromise({ data: e.data, ports: e.ports, error: false });
  }

  onmessageerror = function(e) {
    resolvePromise({ error: true });
  }

  runTests({
    clonableObjectsEveryWhere: true,
    clonableObjectsSameProcess: true,
    transferableObjects: true,
    send(what, ports) {
      return new Promise(function(r, rr) {
        resolve = r;

        try {
          postMessage(what, '*', ports);
        } catch(e) {
          resolve = null;
          rr();
        }
      });
    },

    finished() {
      onmessage = null;
      onmessageerror = null;
      next();
    }
  });
});

// iframe helper class
function test_windowToIframeURL(url, clonableObjectsSameProcess) {
  var resolve;

  onmessage = function(e) {
    if (!resolve) {
      ok(false, "Unexpected message!");
      return;
    }

    let tmp = resolve;
    resolve = null;
    tmp({ data: e.data, ports: e.ports, error: e.data === "error" });
  }

  var ifr = document.createElement('iframe');
  ifr.src = url;
  ifr.onload = function() {
    runTests({
      clonableObjectsEveryWhere: true,
      clonableObjectsSameProcess,
      transferableObjects: true,
      send(what, ports) {
        return new Promise(function(r, rr) {
          resolve = r;
          try {
            ifr.contentWindow.postMessage(what, '*', ports);
          } catch(e) {
            resolve = null;
            rr();
          }
        });
      },

      finished() {
        document.body.removeChild(ifr);
        onmessage = null;
        next();
      }
    });
  }
  document.body.appendChild(ifr);
}

// PostMessage to iframe
tests.push(function test_windowToIframe() {
  info("Testing window to iframe");
  test_windowToIframeURL('iframe_postMessages.html', true);
});

// PostMessage to cross-origin iframe
tests.push(function test_windowToCrossOriginIframe() {
  info("Testing window to cross-origin iframe");
  test_windowToIframeURL('http://example.com/tests/dom/base/test/iframe_postMessages.html', false);
});

SimpleTest.waitForExplicitFinish();
next();

</script>
</body>
</html>
