/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const RELATIVE_DIR = "toolkit/components/pdfjs/test/";
const TESTROOT = "https://example.com/browser/" + RELATIVE_DIR;

function waitForFullScreenState(browser, state) {
  return new Promise(resolve => {
    let eventReceived = false;

    let observe = () => {
      if (!eventReceived) {
        return;
      }
      Services.obs.removeObserver(observe, "fullscreen-painted");
      resolve();
    };
    Services.obs.addObserver(observe, "fullscreen-painted");

    browser.documentGlobal.addEventListener(
      `MozDOMFullscreen:${state ? "Entered" : "Exited"}`,
      () => {
        eventReceived = true;
      },
      { once: true }
    );
  });
}

/**
 * Test that we can enter in presentation mode in using the keyboard shortcut
 * without having to interact with the pdf.
 */
add_task(async function test() {
  let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
  let handlerInfo = mimeService.getFromTypeAndExtension(
    "application/pdf",
    "pdf"
  );

  // Make sure pdf.js is the default handler.
  is(
    handlerInfo.alwaysAskBeforeHandling,
    false,
    "pdf handler defaults to always-ask is false"
  );
  is(
    handlerInfo.preferredAction,
    Ci.nsIHandlerInfo.handleInternally,
    "pdf handler defaults to internal"
  );

  info("Pref action: " + handlerInfo.preferredAction);

  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:blank" },
    async function (browser) {
      // check that PDF is opened with internal viewer
      await waitForPdfJS(browser, `${TESTROOT}file_pdfjs_test.pdf`);

      let fullscreenPromise = waitForFullScreenState(browser, true);

      await SpecialPowers.spawn(browser, [], async function () {
        const { ContentTaskUtils } = ChromeUtils.importESModule(
          "resource://testing-common/ContentTaskUtils.sys.mjs"
        );
        const EventUtils = ContentTaskUtils.getEventUtils(content);
        await EventUtils.synthesizeKey(
          "p",
          { ctrlKey: true, altKey: true },
          content
        );
      });

      await fullscreenPromise;
      ok(true, "Should be in fullscreen");

      fullscreenPromise = waitForFullScreenState(browser, false);
      await SpecialPowers.spawn(browser, [], async function () {
        const { ContentTaskUtils } = ChromeUtils.importESModule(
          "resource://testing-common/ContentTaskUtils.sys.mjs"
        );
        const EventUtils = ContentTaskUtils.getEventUtils(content);
        await EventUtils.synthesizeKey("KEY_Escape", null, content);
      });
      await fullscreenPromise;
      ok(true, "Shouldn't be in fullscreen");

      await waitForPdfJSClose(browser);
    }
  );
});
