<!DOCTYPE HTML>
<html>
<head>
  <title>Test suspending media by inactive docShell</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script src="manifest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<video id="testVideo" src="gizmo.mp4" loop></video>
<script class="testbody" type="text/javascript">
/**
 * When calling `browser.suspendMediaWhenInactive`, it can set the docShell's
 * corresponding flag that is used to suspend media when the docShell is
 * inactive. This test is used to check if we can suspend/resume the media
 * correctly when changing docShell's active state.
 */
async function startTest() {
  const video = document.getElementById("testVideo");

  info(`start video`);
  await video.play();

  info(`set docShell inactive which would suspend media`);
  await setDocShellActive(false);

  info(`set docShell active which would resume media`);
  await setDocShellActive(true);

  SimpleTest.finish();
}

SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv(
  {"set": [["media.testing-only-events", true]]}, startTest);

/**
 * The following are test helper functions.
 */
function mediaSuspendedStateShouldEqualTo(expected) {
  const video = document.getElementById("testVideo");
  const result = SpecialPowers.wrap(video).isSuspendedByInactiveDocOrDocShell;
  is(result, expected, `media's suspended state is correct`);
}

function setDocShellActive(isActive) {
  const win = SpecialPowers.wrap(window);
  const docShell = win.docShell;
  const browsingContext = win.browsingContext;
  // This flag is used to prevent media from playing when docShell is inactive.
  browsingContext.top.suspendMediaWhenInactive = true;
  browsingContext.isActive = isActive;
  // After updating `docshell.isActive`, it would suspend/resume media and we
  // wait suspending/resuming finishing by listening to `MozMediaSuspendChanged`
  return new Promise(r => {
    docShell.chromeEventHandler.addEventListener("MozMediaSuspendChanged",
      () => {
        mediaSuspendedStateShouldEqualTo(!isActive);
        r();
      }, {once : true}
    );
  });
}

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