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

/**
 * Test TrustPanel on pages with certificate override.
 */

"use strict";

async function loadBadCertPage(url) {
  const loaded = BrowserTestUtils.waitForErrorPage(gBrowser.selectedBrowser);
  const loadFlagsSkipCache =
    Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY |
    Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  BrowserTestUtils.startLoadingURIString(
    gBrowser.selectedBrowser,
    url,
    loadFlagsSkipCache
  );
  await loaded;
  await SpecialPowers.spawn(gBrowser.selectedBrowser, [], async () => {
    const netErrorCard =
      content.document.querySelector("net-error-card").wrappedJSObject;
    await netErrorCard.getUpdateComplete();
    EventUtils.synthesizeMouseAtCenter(
      netErrorCard.advancedButton,
      {},
      content
    );
    await ContentTaskUtils.waitForCondition(() => {
      return (
        netErrorCard.exceptionButton && !netErrorCard.exceptionButton.disabled
      );
    }, "Waiting for exception button");
    netErrorCard.exceptionButton.scrollIntoView(true);
    EventUtils.synthesizeMouseAtCenter(
      netErrorCard.exceptionButton,
      {},
      content
    );
  });
  await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
}

function fetchIconUrl(doc, id) {
  let icon = doc.defaultView.getComputedStyle(
    doc.getElementById(id)
  ).listStyleImage;
  return icon.match(/url\("([^"]+)"\)/)?.[1] ?? null;
}

add_setup(async function setup() {
  await SpecialPowers.pushPrefEnv({
    set: [["browser.urlbar.trustPanel.featureGate", true]],
  });
});

add_task(async () => {
  registerCleanupFunction(() => {
    // Remove Exception
    let certOverrideService = Cc[
      "@mozilla.org/security/certoverride;1"
    ].getService(Ci.nsICertOverrideService);
    certOverrideService.clearValidityOverride(
      "self-signed.example.com",
      -1,
      {}
    );
  });
  await loadBadCertPage("https://self-signed.example.com");

  Assert.equal(
    fetchIconUrl(window.document, "trust-icon"),
    "chrome://browser/skin/trust-icon-insecure.svg",
    "Trustpanel urlbar icon shows insecure"
  );
});
