<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test the password manager code called on DOMInputPasswordAdded runs when it occurs between DOMContentLoaded and load events</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script src="pwmgr_common.js"></script>
  <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
</head>
<body>
  <!-- In cases where the "DOMContentLoaded" event for a page has occured but not the "load" event when
  "DOMInputPasswordAdded" fires, we want to make sure that the Password Manager code (i.e.
  _fetchLoginsFromParentAndFillForm) still runs on the page.
  This scenario can happen for example when a page has very little initial HTML, but extensive JS that
  adds Custom Elements or other HTML later, or when other subresources, like images, take a while to load.
  In this test, we delay the page load with a delayed response for an image source. -->
<script type="application/javascript">

let DEFAULT_ORIGIN = window.location.origin;
let FILE_PATH = "/tests/toolkit/components/passwordmgr/test/mochitest/slow_image.html";

async function openDocumentInWindow(win) {
  let DOMContentLoadedPromise = new Promise((resolve) => {
    win.addEventListener("DOMContentLoaded", function() {
      resolve();
    }, {once: true});
  });
  win.location = DEFAULT_ORIGIN + FILE_PATH;
  await DOMContentLoadedPromise;
}

add_setup(async () => {
  await setStoredLoginsAsync([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "user", "omgsecret!"]);
});

add_task(async function test_password_autofilled() {
  let numLogins = await LoginManager.countLogins(DEFAULT_ORIGIN, DEFAULT_ORIGIN, null);
  is(numLogins, 1, "Correct number of logins");

  let win = window.open("about:blank");
  SimpleTest.registerCleanupFunction(() => win.close());
  await openDocumentInWindow(win);
  let processedPromise = promiseFormsProcessed();
  await SpecialPowers.spawn(win, [], function() {
    let doc = this.content.document;
    info("Adding password input field to the page to trigger DOMInputPasswordAdded");
    let passwordField = doc.createElement("input");
    passwordField.type = "password";
    is(doc.readyState, "interactive", "Make sure 'DOMContentLoaded' has fired but not 'load'");
    doc.body.append(passwordField);
  });
  info("Waiting for the password field to be autofilled");
  await processedPromise;
  let expectedValue = "omgsecret!";
  await SpecialPowers.spawn(win, [expectedValue], expectedValueF => {
    is(this.content.document.querySelector("input[type='password']").value, expectedValueF, "Ensure the password field is autofilled");
  });
});
</script>
</body>
</html>
