// Handles loading in company data

const saveButtonHTML =
  `<div class="centeredSection">
    <button id="saveButton" class="button" >Add to FreeAgent</button>
  </div>`

let curProfileDetails = null;

async function receiveDetails(res) {
  if (!res)
    return;
  if (res.type !== "company") {
    navigate(res.url);
    return;
  }

  showProfile(res.details)
}
let profileLock = null
async function showProfile(details) {

  if (profileLock) {
    if (profileLock !== details.id) {
      window.location.replace('company.html')
    }
    return
  }
  profileLock = details.lisn;
  curProfileDetails = details;
  const detailDiv = document.getElementById("details")
  console.log("received company!")
  if (curProfileDetails) {
    detailDiv.innerHTML = "";
    detailDiv.insertAdjacentHTML("afterbegin", companyHTML(curProfileDetails));
    const accountRes = await getAccount(curProfileDetails.companyName, curProfileDetails.lisn)
    const saveButton = document.getElementById("saveButton");
    const linkDiv = document.getElementById('link-div')
    if (saveButton)
      saveButton.remove()
    if (linkDiv)
      linkDiv.remove()
    if (accountRes) {
      if (accountRes === -1) {
        detailDiv.insertAdjacentHTML("afterend", saveButtonHTML);
        const saveButton = document.getElementById("saveButton");
        saveButton.addEventListener("click", async () => {
          setLoadingButton(saveButton);
          const infoInputs = document.getElementsByClassName('infoInput')
          for (const infoInput of infoInputs) {
            curProfileDetails[infoInput.id] = infoInput.value
          }
          const ownerId = await getFromStorage("uid")
          curProfileDetails.owner = ownerId
          const res = await createAccount(curProfileDetails);
          if (!res) {
            runToast('Error sending to FreeAgent', 'fail')
          }
          if (res.hasOwnProperty('errors')) {
            alert('Error occurred:\n' + res.errors[0].message)
            runToast('Error sending to FreeAgent', 'fail')
          }
          else {
            runToast('Company saved to FreeAgent!', 'success')
          }
          removeLoadingToButton(saveButton);

          showProfile(curProfileDetails);
        });
      }
      else {
        const url = faURL + "logo/view/" + accountRes
        createLinkButton(detailDiv, url, false, "See on FreeAgent")


      }
    }
    else {
      runToast("Error: unable to query for account", "fail")
    }
    const getPromise = new Promise((resolve) => {
      chrome.storage.sync.get("curProfileLink", (res) => {
        if (res.hasOwnProperty("curProfileLink")) {
          resolve(res.curProfileLink)
        }
        else {
          resolve(null)
        }
      })
    })
    const profileURL = await getPromise;
    if (profileURL) {
      const contentE = document.getElementsByClassName('content')[0]
      createLinkButton(contentE, profileURL, true, "Go back to profile",
        async () => {
          const savePromise = new Promise((resolve) => {
            chrome.storage.sync.set({
              curProfileLink: ""
            }, resolve)
          })
          await savePromise;
        })

    }
    removeOverlay();
    await openFrame();
  }
  else {
    alert("Error displaying profile")

  }
  profileLock = null;
}

async function init() {
  setOverlay('loading')
  checkLogin();
  initFocusListeners();
  initCloseButton();
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  chrome.tabs.sendMessage(tab.id, { action: "sendDetails" }, receiveDetails)
  /*
  chrome.storage.sync.get("curProfileLink",(res)=>{
    if(res.curProfileLink)
  })
  */
}
init();
