<!DOCTYPE HTML>
<html>
<!--
Bug 1246341: Report message delivery failures to the Push server.

Any copyright is dedicated to the Public Domain.
http://creativecommons.org/licenses/publicdomain/

-->
<head>
  <title>Test for Bug 1246341</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="/tests/dom/push/test/test_utils.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1246341">Mozilla Bug 1246341</a>
<p id="display"></p>
<div id="content" style="display: none">

</div>
<pre id="test">
</pre>

<script class="testbody" type="text/javascript">
  var pushNotifier = SpecialPowers.Cc["@mozilla.org/push/Notifier;1"]
                                  .getService(SpecialPowers.Ci.nsIPushNotifier);

  var reporters = new Map();

  var registration;
  add_task(async function start() {
    await setupPrefsAndReplaceService({
      reportDeliveryError(messageId, reason) {
        ok(reporters.has(messageId),
          "Unexpected error reported for message " + messageId);
        var resolve = reporters.get(messageId);
        reporters.delete(messageId);
        resolve(reason);
      },
    });
    await setPushPermission(true);

    var url = "error_worker.js?" + (Math.random());
    registration = await navigator.serviceWorker.register(url, {scope: "."});
    await waitForActive(registration);
  });

  var controlledFrame;
  add_task(async function createControlledIFrame() {
    controlledFrame = await injectControlledFrame();
  });

  var idCounter = 1;
  function waitForDeliveryError(request) {
    return new Promise(resolve => {
      var data = new TextEncoder().encode(JSON.stringify(request));
      var principal = SpecialPowers.wrap(window).clientPrincipal;

      let messageId = "message-" + (idCounter++);
      reporters.set(messageId, resolve);
      pushNotifier.notifyPushWithData(registration.scope, principal, messageId,
                                      data);
    });
  }

  add_task(async function reportDeliveryErrors() {
    var reason = await waitForDeliveryError({ type: "exception" });
    is(reason, SpecialPowers.Ci.nsIPushErrorReporter.DELIVERY_UNCAUGHT_EXCEPTION,
      "Should report uncaught exceptions");

    reason = await waitForDeliveryError({ type: "rejection" });
    is(reason, SpecialPowers.Ci.nsIPushErrorReporter.DELIVERY_UNHANDLED_REJECTION,
      "Should report unhandled rejections");
  });

  add_task(async function reportDecryptionError() {
    var message = await new Promise(resolve => {
      SpecialPowers.registerConsoleListener(msg => {
        if (!msg.isScriptError && !msg.isConsoleEvent) {
          return;
        }
        const scope = "http://mochi.test:8888/tests/dom/push/test/";
        if (msg.innerWindowID === "ServiceWorker" &&
            msg.windowID === scope) {
          SpecialPowers.postConsoleSentinel();
          resolve(msg);
        }
      });

      var principal = SpecialPowers.wrap(window).clientPrincipal;
      pushNotifier.notifyError(registration.scope, principal, "Push error",
        SpecialPowers.Ci.nsIScriptError.errorFlag);
    });

    is(message.sourceName, registration.scope,
      "Should use the qualified scope URL as the source");
    is(message.errorMessage, "Push error",
      "Should report the given error string");
  });

  add_task(async function unsubscribe() {
    controlledFrame.remove();
  });

  add_task(async function unregister() {
    await registration.unregister();
  });

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