// Handles showing saved profiles as well as sending these saved profiles to FreeAgent

let detailDiv = document.getElementById("details")
let faButton = document.getElementById("faButton");
const contactTagInput = document.getElementById("tag-input");
const contactTags = document.getElementById("contact-lists");
window.addEventListener("unhandledrejection", function (promiseRejectionEvent) {
  removeOverlay()

  runToast('Error happened while exporting', 'fail')
  console.log(promiseRejectionEvent);
});
faButton.addEventListener("click", async () => {
  try {
    setLoadingButton(faButton);
    setOverlay('sending');
    const res = await sendProfilesToFA();
    removeLoadingToButton(faButton);
    if (res.success)
      runToast('Profiles saved!', 'success')
    else
      runToast('Error: Remaining profile(s) caused export error', 'fail')

  }
  catch (e) {
    removeOverlay();
    runToast('Error happened while exporting', 'fail')
    console.log(e);

  }
  await loadView(true);
  removeOverlay();
});

async function loadView(afterExport = false) {
  //setOverlay("loading")
  await updateContactListInput();
  loadSavedProfiles(afterExport);
  //removeOverlay();
}
function loadSavedProfiles(afterExport = false) {
  chrome.storage.sync.get(null, (res) => {
    detailDiv.innerHTML = "";

    if (res.profiles.length === 0) {
      setLoadingButton(faButton);
      let title = "No queued profiles"
      let subtitle = "Add some from Current Profile!"
      if (afterExport) {
        title = "Export Successful!"
        subtitle = "Sent profiles to FreeAgent"
      }
      const html = `
      <section class="splash">
        <h3 class="splash_title">${title}</h3>
        <p class="splash_sub">${subtitle}</p>
      </section>`
      detailDiv.insertAdjacentHTML("afterbegin", html)
    }
    for (const profileIndex in res.profiles) {
      const profile = res.profiles[profileIndex]
      const profId = "saved" + String(profileIndex);
      const deleteId = "del" + String(profileIndex);
      const finalHtml = `
        <div class="profile-card">
          ${profileHTML(profile, true, profId)}
          <div class="centeredSection"><button id="${deleteId}" class="button button_line">Remove</button></div>
        </div>
      `

      detailDiv.insertAdjacentHTML("afterbegin", finalHtml);
      const nameText = document.querySelector(`#${profId} .info-name`)
      nameText.onclick = () => { changeWindowURL(profile.linkedInSalesNav) };
      const deleteButton = document.getElementById(deleteId);
      deleteButton.addEventListener("click", () => {
        promptDeleteProfile(profileIndex)
      });
    }
  });
}
async function updateContactListInput() {
  if (!faURL.includes('staging'))
    return;
  const faTags = await getTags();
  let tags = faTags.sort();
  contactTags.innerHTML = "";
  for (const tag of tags) {
    const newOption = document.createElement('option')
    newOption.value = tag;
    contactTags.insertAdjacentElement("beforeend", newOption);
  }
}

function sendProfilesToFA() {
  return new Promise((resolve, reject) => {
    let success = true
    let results = []
    let accounts = {}
    chrome.storage.sync.get(["profiles", "lists", "uid", "lead_source_id"], async (res) => {
      const tag = contactTagInput.value
      for (let i = res.profiles.length - 1; i >= 0; i--) {
        const profile = res.profiles[i];
        profile.owner = res.uid
        profile.source_id = res.lead_source_id;
        profile.list = tag

        let accountID;
        if (accounts.hasOwnProperty(profile.companyName))
          accountID = accounts[profile.companyName];
        else {
          accountID = await getAccount(profile.companyName, profile.companyLISN);
          if (accountID) {
            if (accountID === -1) {
              const companyRes = await createAccountForProfile(profile)
              if (companyRes && !companyRes.hasOwnProperty('errors')) {

                accountID = companyRes.data.createEntity.entity_value.id
                accounts[profile.companyName] = accountID;
              }
              else {
                const errorMessage = companyRes.errors[0].message;
                alert(`Failed to import ${profile.companyName}:\n${errorMessage}`);
                resolve({ success: false, results: null });

              }
            }
            else {
              accounts[profile.companyName] = accountID;

            }
          }
        }
        const result = await createContactFromProfile(profile, accountID);
        if (!result.hasOwnProperty('errors')) {
          await deleteProfile(i);
        }
        else {
          let errorMessage = result.errors[0].message;
          //errorMessage = JSON.parse(errorMessage).message
          alert(`Failed to import ${profile.firstName + " " + profile.lastName}:\n${errorMessage}`);
          success = false
        }
        results.push(result);
      }
      resolve({ success, results });
    });
  });
}

function promptDeleteProfile(profileIndex) {
  const deleteFunc = async () => {
    await deleteProfile(profileIndex);
    loadSavedProfiles();
    removeOverlay();
  }
  const cancelFunc = () => {
    removeOverlay();
  }
  setOverlay("delete", deleteFunc, cancelFunc);


}

function init() {
  checkLogin();
  loadView();
  initCloseButton();
  const currentLink = document.getElementById('current-link')
  currentLink.onclick = () => { window.location.replace('current.html') }
}
init();


