<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>Test DocumentL10n Telemetry</title>
  <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
  <script type="application/javascript">
  "use strict";
  const { BrowserTestUtils } = ChromeUtils.import(
    "resource://testing-common/BrowserTestUtils.jsm"
  );

  SimpleTest.waitForExplicitFinish();

  function countValues(snapshot, key) {
    if (!snapshot.hasOwnProperty(key)) {
      return 0;
    }
    let values = snapshot[key].values;
    return Object.values(values).reduce((sum, n) => sum + n, 0);
  }

  (async function() {
      let histogram = Services.telemetry
          .getKeyedHistogramById("L10N_DOCUMENT_INITIAL_TRANSLATION_TIME_US");
      let snapshot = histogram.snapshot();

      // In some cases the test runs before first window is localized.
      // We just want to ensure that we didn't register more than 1
      // first window telemetry.
      let firstWindowCount = countValues(snapshot, "browser_first_window");
      is(firstWindowCount < 2, true);

      histogram.clear();

      // Open a new window
      let win = await BrowserTestUtils.openNewBrowserWindow({
        waitForTabURL: "about:blank",
      });

      // Telemetry in testing is flaky and when landing this test
      // we saw cases where the snapshot did not contain the new
      // window telemetry at this moment.
      //
      // We're going to use `waitForCondition` to test for
      // the telemetry to be eventually recorded.
      BrowserTestUtils.waitForCondition(() => {
          snapshot = histogram.snapshot();

          // We want to make sure that since we cleared histogram
          // just one new window of either type has been opened.
          let browserWindowsCount =
              countValues(snapshot, "browser_new_window") +
              countValues(snapshot, "browser_first_window");
          return browserWindowsCount == 1;
      });

      // Open preferences in a new tab
      let tab = BrowserTestUtils.addTab(
          win.gBrowser,
          "about:preferences"
      );
      await BrowserTestUtils.browserLoaded(tab.linkedBrowser);

      // Similarly to the above, we've seen cases where the telemetry
      // was not present right after the tab was opened, so
      // we'll use `waitForCondition` here.
      BrowserTestUtils.waitForCondition(() => {
          snapshot = histogram.snapshot();

          return countValues(snapshot, "about:preferences") == 1;
      });

      await BrowserTestUtils.closeWindow(win);

      SimpleTest.finish();
  })();
  </script>
</head>
<body>
</body>
</html>
