<!-- Any copyright is dedicated to the Public Domain.
   - http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
  <title>Test hidden frames</title>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script type="text/javascript" src="mock_gamepad.js"></script>
<script class="testbody" type="text/javascript">
let ok = window.parent.ok;
let is = window.parent.is;
let SimpleTest = window.parent.SimpleTest;
let SpecialPowers = window.parent.SpecialPowers;

window.addEventListener("gamepadbuttondown", function() {
  // Wait to ensure that all frames received the button press as well.
 SpecialPowers.executeSoon(tests[testNum++]);
});

async function pressButton() {
  await GamepadService.newButtonEvent(index, 0, true, true);
  await GamepadService.newButtonEvent(index, 0, false, false);
}

function setFrameVisible(f, visible) {
  SpecialPowers.wrap(f.contentWindow).browsingContext.isActive = visible;
}

var frames_loaded = 0;
async function startTest() {
  frames_loaded++;
  if (frames_loaded != 2) return;
  index = await GamepadService.addGamepad("test gamepad", // id
                              GamepadService.standardMapping,
                              GamepadService.noHand,
                              4, // buttons
                              2,
                              0,
                              0,
                              0);

  await gamepad_loaded();
}
var f1, f2;
async function gamepad_loaded() {
  f1 = document.getElementById('f1');
  f2 = document.getElementById('f2');
  await pressButton();
}



var testNum = 0;
var tests = [
  test1,
  test2,
];

function test1() {
  is(f1.contentWindow.buttonPresses, 1, "right number of button presses in frame 1");
  is(f2.contentWindow.buttonPresses, 1, "right number of button presses in frame 2");

  // Now hide the second frame and send another button press.
  setFrameVisible(f2, false);
  SpecialPowers.executeSoon( async () => { await pressButton(); });
}

async function test2() {
  is(f1.contentWindow.buttonPresses, 2, "right number of button presses in frame 1");
  is(f2.contentWindow.buttonPresses, 1, "right number of button presses in frame 2");
  await GamepadService.removeGamepad(index);
  SimpleTest.finish();
}

</script>
<iframe id="f1" src="gamepad_frame.html" onload="runGamepadTest(startTest)"></iframe>
<iframe id="f2" src="gamepad_frame.html" onload="runGamepadTest(startTest)"></iframe>
</body>
</html>
