// Handles scraping person profile details

let curProfileDetails = null;
let saveButton = document.getElementById("saveButton");
let validCompany = false
let detailDiv = document.getElementById("details")
let updateIndex = -1;
saveButton.addEventListener("click", async () => {
  setLoadingButton(saveButton);
  const infoInputs = document.getElementsByClassName('infoInput')
  for (const infoInput of infoInputs) {
    curProfileDetails[infoInput.id] = infoInput.value
  }
  const contactInputs = document.getElementsByClassName('contactInput')
  for (const contactInput of contactInputs) {
    curProfileDetails.contactInfo[contactInput.id] = contactInput.value
  }
  const status = await saveProfile(curProfileDetails, updateIndex)
  removeLoadingToButton(saveButton);
  if (status === 0)
    runToast('Profile saved!', 'success')
  else
    runToast('Failed to save profile!', 'fail')

  showProfile(curProfileDetails);
});


async function receiveDetails(res) {
  if (!res)
    return;
  if (res.type !== "profile") {
    navigate(res.url);
    return;
  }
  const curProfile = await getCurProfile()
  if (curProfile?.id === res.details.id) {
    showProfile(curProfile)
  }
  else {
    showProfile(res.details)

  }
}
let profileLock = null
async function showProfile(details) {
  console.log(">>> checking")
  if (profileLock) {
    if (profileLock !== details.id) {
      window.location.replace('current.html')
    }
    return
  }
  profileLock = details.id;
  saveCurProfile(details)
  curProfileDetails = details;
  console.log("received profile!")
  if (curProfileDetails) {
    const { isSaved, index, profile } = await isSavedProfile(curProfileDetails)
    if (isSaved) {
      saveButton.innerHTML = 'Update';
      curProfileDetails = profile;
    }
    else {
      saveButton.innerHTML = 'Queue';
    }
    updateIndex = index;
    detailDiv.innerHTML = "";
    detailDiv.insertAdjacentHTML("afterbegin", profileHTML(curProfileDetails));
    const infoInputs = document.getElementsByClassName('infoInput')
    for (const infoInput of infoInputs) {
      infoInput.addEventListener('change', async (e) => {
        console.log("saving profile?")
        curProfileDetails[infoInput.id] = e.target.value;
        await saveCurProfile(curProfileDetails)
      })
    }
    removeLoadingToButton(saveButton);
    const companyInput = document.getElementById('companyName')
    companyInput.addEventListener('focusin', () => {
      setLoadingButton(saveButton);
    })
    companyInput.addEventListener('focusout', async (e) => {
      if (curProfileDetails.companyName === e.target.value) {
        if (validCompany)
          removeLoadingToButton(saveButton);
        else
          return
      }
      else {
        console.log("input changed")
        curProfileDetails.companyName = e.target.value
        setOverlay('loading')
        await checkFA()
        removeOverlay('loading')

      }
    })

    await checkFA();

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

async function checkFA() {
  const linkDiv = document.getElementById('link-div')
  const companyWarning = document.getElementById('company-warning')
  if (linkDiv)
    linkDiv.remove();
  if (companyWarning)
    companyWarning.remove();

  const res = await getFAContact(curProfileDetails);
  removeLoadingToButton(saveButton);
  if (res && res.data.listEntityValues.count > 0) {
    const url = faURL + "contact/view/" + res.data.listEntityValues.entity_values[0].id
    createLinkButton(detailDiv, url, false, "See on FreeAgent")
    setLoadingButton(saveButton);
  }
  else {
    const accountRes = await getAccount(curProfileDetails.companyName, curProfileDetails.companyLISN)
    validCompany = true;
    if (accountRes && accountRes === -1) {
      const spanE = document.createElement('span')
      spanE.id = "company-warning"
      spanE.innerHTML = "No account found for company!"
      const cDiv = document.createElement('div')
      cDiv.classList = "centeredSection"
      cDiv.insertAdjacentElement("afterbegin", spanE)
      detailDiv.insertAdjacentElement("beforeend", cDiv)
      validCompany = false
      if (curProfileDetails.companyLISN) {
        setLoadingButton(saveButton);
        const linkDiv = createLinkButton(detailDiv, curProfileDetails.companyLISN, true, "Go to Company Page",
          async () => {
            const savePromise = new Promise((resolve) => {
              chrome.storage.sync.set({
                curProfileLink: curProfileDetails.linkedInSalesNav
              }, resolve)
            })
            await savePromise;
          })

      }
      else {
        spanE.innerHTML += "\n\nOne will be created automatically."
      }
    }
  }
}
async function init() {
  setLoadingButton(saveButton);
  setOverlay('loading')
  initFocusListeners();
  checkLogin();
  initCloseButton();
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  const queuedLink = document.getElementById('queued-link')
  queuedLink.onclick = () => { window.location.replace('saved.html') }
  chrome.tabs.sendMessage(tab.id, { action: "sendDetails", tabId: tab.id }, receiveDetails)
}
init();

async function test() {
  const result = await resolveTID("459c8db9-a729-4949-81c6-14e8bd50b76b", 'catalog_type')
  console.log(">>>Test")
  console.log(result)
}
//test();