function setIndicator({ icon, badgeText, badgeColor }) {
  chrome.action.setIcon({ path: `../img/${icon}` });
  chrome.action.setBadgeText({ text: badgeText });
  chrome.action.setBadgeBackgroundColor({ color: badgeColor });
}

async function getRingManifest(ringUrl) {
  const url = `${ringUrl}/api/manifest`;
  let res = await fetch(url);
  if (!res) throw new Error("Ring manifest fetch failed");
  if(res.ok) {
    return await res.json();
  }
}

async function siteStanding(ringUrl, manifest, standingDiv, validationResultSpan) {
  try {
    let res = await fetch(`${ringUrl}/api/member/standing`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({url: manifest.url})
    });
    if (res.ok) {
      const standingResult = await res.json();
      console.log(standingResult);
      const standing = standingResult.standing;
      standingDiv.querySelector(".standing").innerText = `Standing: ${standing}`;
      const goodLi = document.createElement("li");
      goodLi.innerText = `Good: ${standingResult.vote_split.good}`;
      standingDiv.querySelector(".split-list").appendChild(goodLi);
      const badLi = document.createElement("li");
      badLi.innerText = `Bad: ${standingResult.vote_split.bad}`;
      standingDiv.querySelector(".split-list").appendChild(badLi);
      const neutralLi = document.createElement("li");
      neutralLi.innerText = `Good: ${standingResult.vote_split.neutral}`;
      standingDiv.querySelector(".split-list").appendChild(neutralLi);
      document.querySelector("#descriptions").classList.remove("hidden");
      standingResult.descriptions.forEach(d => {
        const description = document.createElement("li");
        description.innerText = d;
        standingDiv.querySelector(".descriptions").appendChild(description);
      });
      if (standing === "Bad") {
        validationResultSpan.innerText += " | Bad Standing"
        setIndicator({
          icon: "icon-warning.png",
          badgeText: "!",
          badgeColor: "#fc8f08ff"
        });
      } else if (standing === "Good") {
        validationResultSpan.innerText += " | Good Standing"
      } else {
        validationResultSpan.innerText += " | Neutral Standing"
      }
    }
  } catch (error) {
    console.error(error);
  }
}

async function validateRing(ringUrl, manifestResponse, validationResultSpan) {
  try {
    let res = await fetch(`${ringUrl}/api/member/validate`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(manifestResponse)
    });
    if (!res.ok) {
      const text = await res.text();
      validationResultSpan.classList.add("failure");
      validationResultSpan.innerText = `Failure: ${text}`;
      setIndicator({
        icon: "icon-failure.png",
        badgeText: "!",
        badgeColor: "#d82107ff"
      });
      return;
    }
    const validationResult = await res.json();
    if (validationResult.result === "success") {
      validationResultSpan.classList.add("success");
      validationResultSpan.innerText = "Validation passed!";
      setIndicator({
        icon: "icon-success.png",
        badgeText: "✓",
        badgeColor: "#24c406ff"
      });
    } else {
      validationResultSpan.classList.add("failure");
      validationResultSpan.innerText = "Validation failed";
      setIndicator({
        icon: "icon-failure.png",
        badgeText: "!",
        badgeColor: "#d82107ff"
      });
    }
  } catch (error){
    console.log(error);
    validationResultSpan.classList.add("warning");
    validationResultSpan.innerText = `Error: ${error}`;
    setIndicator({
      icon: "icon-warning.png",
      badgeText: "!",
      badgeColor: "#fc8f08ff"
    });
  }
}

async function populateDetails(manifestResponse) {
  const manifest = manifestResponse.manifest;
  // Site name
  document.querySelector("#site-name").innerText = manifest.name;
  document.querySelector("#site-description").innerText = manifest.description;
  document.querySelector("#site-public-key").innerText = manifest.keyset.keys[0].x

  Object.keys(manifest.rings).forEach(async (ringUrl) => {
    const ringManifest = await getRingManifest(ringUrl);
    console.log(ringManifest);
    const ringData =ringManifest.manifest;
    const sigKey = ringData.keyset.keys[0].x;
    const encKey = ringData.keyset.keys[1].x;
    console.log(ringData.keyset.keys);
    // <div class="ring-data-container">
    const ringDiv = document.createElement("div");
    ringDiv.classList.add("ring-data-container");

    // <h4><a href="ring-url">
    const ringHeader = document.createElement("h4");
    const ringLink = document.createElement("a");
    ringLink.href = ringUrl;
    ringLink.innerText = ringData.name;
    ringHeader.appendChild(ringLink);
    ringDiv.appendChild(ringHeader);


    //<p>ringDescription</p>
    const ringDescription = document.createElement("p");
    ringDescription.innerText = ringData.description;
    ringDiv.appendChild(ringDescription);

    //<p>ringPubKey</p>
    const ringPubSigningKey = document.createElement("p");
    ringPubSigningKey.classList.add("public-key");
    ringPubSigningKey.innerText = `Public Signing Key: ${sigKey}`;
    ringDiv.appendChild(ringPubSigningKey);

    //<p>ringPubKey</p>
    const ringPubEncryptionKey = document.createElement("p");
    ringPubEncryptionKey.classList.add("public-key");
    ringPubEncryptionKey.innerText = `Public Encryption Key: ${encKey}`;
    ringDiv.appendChild(ringPubEncryptionKey);

    //<div class="members">
    const membersDiv = document.createElement("div");
    membersDiv.classList.add("members");
    Object.keys(ringManifest.manifest.members).forEach(m => {
      const member = ringManifest.manifest.members[m];
      const memberDiv = document.createElement("div");
      memberDiv.classList.add("ring-member");
      const memberUrl = document.createElement("a");
      memberUrl.href = member.url;
      memberUrl.innerText = member.name;
      memberDiv.appendChild(memberUrl);
      membersDiv.appendChild(memberDiv);
    });
    ringDiv.appendChild(membersDiv);

    //<div class="standing-container">
    const standingDiv = document.createElement("div");
    standingDiv.classList.add("standing-container");
    const standing = document.createElement("h3");
    standing.classList.add("standing");
    standingDiv.appendChild(standing);

    //<div class="vote-split>"
    const voteSplit = document.createElement("div");
    voteSplit.classList.add("vote-split");
    //<ul class="split-list">
    const splitList = document.createElement("ul");
    splitList.classList.add("split-list");
    voteSplit.appendChild(splitList);
    standingDiv.appendChild(voteSplit);

    const descriptionsHeader = document.createElement("h4");
    descriptionsHeader.innerText = "Descriptions"
    descriptionsHeader.id = "descriptions";
    descriptionsHeader.classList.add("hidden");
    standingDiv.appendChild(descriptionsHeader);

    //<ul class="descriptions"
    const descriptionsList = document.createElement("ul");
    descriptionsList.classList.add("descriptions");
    standingDiv.appendChild(descriptionsList);


    //<button>Validate</button>
    const validateBtn = document.createElement("button");
    validateBtn.classList.add("validate-btn");
    validateBtn.innerText = "Validate";
    //<span class="validation-result">
    const validationResultSpan = document.createElement("span");
    validationResultSpan.classList.add("validation-result")

    validateBtn.addEventListener("click", async (e) => {
      await validateRing(ringUrl, manifestResponse, validationResultSpan);
      await siteStanding(ringUrl, manifestResponse.manifest, standingDiv, validationResultSpan);
    });

    ringDiv.appendChild(standingDiv);
    ringDiv.appendChild(validateBtn);
    ringDiv.appendChild(validationResultSpan);
    document.querySelector("#ring-list").appendChild(ringDiv);
  })

}




async function main() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  console.log(tab);
  // Ask content script for the last result
  const res = await chrome.tabs.sendMessage(tab.id, { type: "LAST_FETCH" });
  console.log(res);
  if (!res) {
    document.querySelector("#manifest-found").classList.add("hidden");
    document.querySelector("#manifest-missing").classList.add("hidden");
    document.querySelector("#manifest-invalid-origin").classList.add("hidden");
    document.querySelector("#manifest-checking").classList.remove("hidden");
  } else if (res.manifest == null) {
    // No manifest found
    document.querySelector("#manifest-found").classList.add("hidden");
    document.querySelector("#manifest-invalid-origin").classList.add("hidden");
    document.querySelector("#manifest-missing").classList.remove("hidden");
    document.querySelector("#manifest-checking").classList.add("hidden");
    setIndicator({
      icon: "icon-warning.png",
      badgeText: "!",
      badgeColor: "#fc8f08ff"
    });
  } else if (res.manifest.manifest.url !== tab.url.replace(/\/$/, "")) {
    // Manifest found but origin doesn't match
    document.querySelector("#manifest-found").classList.add("hidden");
    document.querySelector("#manifest-missing").classList.add("hidden");
    document.querySelector("#manifest-invalid-origin").classList.remove("hidden");
    document.querySelector("#manifest-checking").classList.remove("hidden");
    document.querySelector(".manifest-details").classList.remove("hidden");
    setIndicator({
      icon: "icon-failure.png",
      badgeText: "!",
      badgeColor: "#d82107ff"
    });
    populateDetails(res.manifest);
  } else  {
    // Manifest found and origin matches
    document.querySelector("#manifest-found").classList.remove("hidden");
    document.querySelector("#manifest-missing").classList.add("hidden");
    document.querySelector("#manifest-invalid-origin").classList.add("hidden");
    document.querySelector("#manifest-checking").classList.add("hidden");
    populateDetails(res.manifest);
    document.querySelector(".manifest-details").classList.remove("hidden");
    setIndicator({
      icon: "icon-found.png",
      badgeText: "",
      badgeColor: "#00000000" // transparent
    });
  }
}

main();
