// Handles user authorization for FreeAgent
const loader = `<section class="loader-section"><div class="loader"></div></section>`

let closeButton = document.getElementById("close-button");

const redirect = chrome.runtime.getURL('redirect.html')
function main() {

  chrome.storage.sync.get(['faKeys'], async (res) => {
    // http://localhost:5000/redirect
    const loginURL = faURL + `dialog/authorize?response_type=code&client_id=${res.faKeys.client_id}&scope=lead%3Acreate%2Cdeal%3Acreate%2Clead%3Aread%2Cdeal%3Aread%2Caccount%3Acreate%2Caccount%3Aread%2Ctask%3Aadd%2Centity%3Aread%2Centity%3Acreate%2Cfield%3Aread&redirect_uri=${redirect}`
    const loginButton = document.getElementById('login');
    loginButton.addEventListener("click", () => {
      window.open(loginURL, '_blank').focus();
    })
    await openFrame();
  });
}

async function leaveLogin() {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (tab.url && tab.url.includes("www.linkedin.com/sales/lead/")) {
    window.location.replace("current.html");
  }
  else {
    window.location.replace("splash.html");
  }
}
function onLoggedIn() {

  const title = document.getElementById('title');
  const subtitle = document.getElementById('subtitle');
  const logo = document.getElementById('logo')
  const loginButton = document.getElementById('login');
  loginButton.remove();
  title.innerHTML = "Successfully paired with FreeAgent!"
  subtitle.innerHTML = "Please wait a moment."
  const mainSection = document.getElementById('main')
  logo.insertAdjacentHTML("afterend", loader)

}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status == 'complete' && tab.url) {
    if (tab.url.includes(redirect + "?code=")) {
      const [_, code] = tab.url.match(/code=(.*)/);
      if (code) {
        chrome.storage.sync.get(['faKeys',], async (res) => {
          const stream = await fetch(faURL + "oauth/token", {
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            method: "POST",
            body: JSON.stringify({
              code,
              client_id: res.faKeys.client_id,
              client_secret: res.faKeys.client_secret,
              grant_type: "authorization_code",
              redirect_uri: redirect,
            }),
          })
          const resJson = await stream.json()
          const { access_token, refresh_token, user_id } = resJson;
          chrome.storage.sync.set({
            access_token,
            refresh_token,
            "uid": user_id
          }, async () => {
            onLoggedIn();
            const queryTagListId = await resolveTID(res.faKeys.tag_list_field_tid, 'field');
            const querySourceId = await resolveTID(res.faKeys.source_tid, "catalog");
            if (queryTagListId && querySourceId) {
              chrome.storage.sync.set({
                "tag_list_id": queryTagListId.data.resolveFieldConfigTransportId.id,
                "lead_source_id": querySourceId.data.resolveCatalogTransportId.id
              });
            }
            else {
              console.log("ERROR: failed to set choice list info");
            }
            setTimeout(leaveLogin, 1000);
          })
        })

      }
    }
  }

});
closeButton.addEventListener("click", async () => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.tabs.sendMessage(tab.id, { action: "toggleFrame" })
});

main()
