<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test handling of different password length</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script src="pwmgr_common.js"></script>
  <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script type="application/javascript">
const { LoginManagerChild } = SpecialPowers.ChromeUtils.import(
  "resource://gre/modules/LoginManagerChild.jsm"
);

let readyPromise = registerRunTests();

let loadPromise = new Promise(resolve => {
  document.addEventListener("DOMContentLoaded", () => {
    document.getElementById("loginFrame").addEventListener("load", (evt) => {
      resolve();
    });
  });
});

async function loadFormIntoIframe(origin, html) {
  let loginFrame = document.getElementById("loginFrame");
  let loadedPromise = new Promise((resolve) => {
    loginFrame.addEventListener("load", function() {
      resolve();
    }, {once: true});
  });
  let processedPromise = promiseFormsProcessed();
  loginFrame.src = origin + "/tests/toolkit/components/passwordmgr/test/mochitest/blank.html";
  await loadedPromise;

  await SpecialPowers.spawn(getIframeBrowsingContext(window, 0), [html], function(contentHtml) {
    // eslint-disable-next-line no-unsanitized/property
    this.content.document.documentElement.innerHTML = contentHtml;
  });

  // Wait for the form to be processed before trying to submit.
  await processedPromise;
}

add_setup(async () => {
  info("Waiting for setup and page and frame loads");
  await readyPromise;
  await loadPromise;
});

const DEFAULT_ORIGIN = window.location.origin;
const TESTCASES = [
  {
    testName: "test_control2PasswordFields",
    pword1: "pass1",
    pword2: "pass2",
    expectedNewPassword: { value: "pass2" },
    expectedOldPassword: { value: "pass1" },
  },
  {
    testName: "test_1characterPassword",
    pword1: "x",
    pword2: "pass2",
    expectedNewPassword: { value: "pass2" },
    expectedOldPassword: null,
  },
  {
    testName: "test_2characterPassword",
    pword1: "xy",
    pword2: "pass2",
    expectedNewPassword: { value: "pass2" },
    expectedOldPassword: { value: "xy" },
  },
  {
    testName: "test_1characterNewPassword",
    pword1: "pass1",
    pword2: "x",
    expectedNewPassword: { value: "pass1" },
    expectedOldPassword: null,
  },
];

/**
 * @return {Promise} resolving when form submission was processed.
 */
function getSubmitMessage() {
  return new Promise((resolve, reject) => {
    PWMGR_COMMON_PARENT.addMessageListener("formSubmissionProcessed", function processed(...args) {
      info("got formSubmissionProcessed");
      PWMGR_COMMON_PARENT.removeMessageListener("formSubmissionProcessed", processed);
      resolve(args[0]);
    });
  });
}

add_task(async function test_password_lengths() {
  for (let tc of TESTCASES) {
    info("Starting testcase: " + tc.testName + ", " + JSON.stringify([tc.pword1, tc.pword2]));
    await loadFormIntoIframe(DEFAULT_ORIGIN, `<form id="form1" onsubmit="return false;">
      <input  type="text"       name="uname" value="myname">
      <input  type="password"   name="pword1" value="">
      <input  type="password"   name="pword2" value="">
      <button type="submit" id="submitBtn">Submit</button>
    </form>`);

    await SpecialPowers.spawn(getIframeBrowsingContext(window, 0), [tc], function(testcase) {
      let doc = this.content.document;
      Assert.equal(doc.querySelector("[name='uname']").value, "myname", "Checking for filled username");
      doc.querySelector("[name='pword1']").setUserInput(testcase.pword1);
      doc.querySelector("[name='pword2']").setUserInput(testcase.pword2);
    });

    // Check data sent via PasswordManager:onFormSubmit
    let processedPromise = getSubmitMessage();
    await SpecialPowers.spawn(getIframeBrowsingContext(window, 0), [], function() {
      this.content.document.getElementById("submitBtn").click();
    });

    let { data } = await processedPromise;
    info("Got submitted result: " + JSON.stringify(data));

    if (tc.expectedNewPassword === null) {
      is(data.newPasswordField,
         tc.expectedNewPassword, "Check expectedNewPassword is null");
    } else {
      is(data.newPasswordField.value,
         tc.expectedNewPassword.value,
         "Check that newPasswordField.value matches the expectedNewPassword.value");
    }
    if (tc.expectedOldPassword === null) {
      is(data.oldPasswordField,
         tc.expectedOldPassword, "Check expectedOldPassword is null");
    } else {
      is(data.oldPasswordField.value,
         tc.expectedOldPassword.value,
         "Check that oldPasswordField.value matches expectedOldPassword.value");
    }
  }
});
</script>

<p id="display"></p>

<div id="content">
  <iframe id="loginFrame" src="/tests/toolkit/components/passwordmgr/test/mochitest/blank.html"></iframe>
</div>
<pre id="test"></pre>
</body>
</html>
