const infoStrings = {
  "firstName": "First Name",
  "lastName": "Last Name",
  "jobTitle": "Job Title",
  "companyName": "Company",
  "location": "Location",
  "numEmployees": "# of Employees",
  "industry": "Industry",
  "revenue": "Revenue",
  "phone": "Phone Number",
  "email": "Email",
  "website": "Website",
  "twitter": "Twitter"
}

function profileHTML(data, isSaved = false, id = "") {
  if (!data)
    return;
  let html = ""
  if (isSaved) {
    html += `<div `
    if (id !== "") {
      html += `id="${id}"`
    }
    html += `class="profile profile-sum">\n`
    if (data.imgSrc !== "")
      html += `<img class="headshot" alt="No Profile Image"src= ${data.imgSrc}>\n`
    html += `<div class='top-info'>`
    html += `<span class="info info-name">${data.firstName + ' ' + data.lastName}</span><br>`
    html += `<span class="info info-job">${data.jobTitle}</span><br>`
    html += `<span class="info info-company">${data.companyName}</span>`
    html += `</div>`
    /*
    Object.keys(data.contactInfo).sort().forEach((key) => {
      html += `\n ${contactStrings[key]}: ${data.contactInfo[key]}`
    });
    */
    //html += `</span>`
    html += `</div>`

  }
  if (!isSaved) {
    if (data.imgSrc !== "")
      html += `<div class="centeredSection"><img class="headshot center" alt="No Profile Image"src= ${data.imgSrc}></div>\n`
    html += `<div class='profile profile__list'>`
    let inputFields = ["firstName", "lastName", "jobTitle", "companyName", "email", "phone"]
    for (const key of inputFields) {
      html += `
    <div class="userInput">
        <span class="inputDesc">${infoStrings[key]}</span>
        <input class="infoInput ui-input" id="${key}" value ="${data[key]}">
    </div>`
    }


    html += `</div>`

  }

  return html
}

function companyHTML(data) {
  let html = ""
  if (data.imgSrc !== "")
    html += `<div class="centeredSection"><img class="company-logo center" alt="No Profile Image"src= ${data.imgSrc}></div>\n`
  html += `<div class='profile profile__list'>`
  let inputFields = ["companyName", "industry", "location", "numEmployees", "revenue", "website"]
  for (const key of inputFields) {
    html += `
  <div class="userInput">
      <span class="inputDesc">${infoStrings[key]}</span>
      <input class="infoInput ui-input" id="${key}" value ="${data[key]}">
  </div>`
  };
  html += `</div>`
  return html;
}

function saveProfile(profileData, updateIndex = -1) {
  if (!profileData) {
    return -1
  }
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(null, (res) => {

      if (updateIndex !== -1) {
        res.profiles[updateIndex] = profileData
      }
      else {
        res.profiles.push(profileData);
      }
      chrome.storage.sync.set(res, () => {
        resolve(0);
      });
    });
  });
}

function deleteProfile(index) {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(["profiles"], (res) => {
      res.profiles.splice(index, 1);
      chrome.storage.sync.set({ profiles: res.profiles }, () => {
        console.log("deleted profile")
        resolve();
      });
    });
  })
}


function isSavedProfile(profile) {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get("profiles", (res) => {
      for (const i in res.profiles) {
        const savedProfile = res.profiles[i]
        if (savedProfile !== null && profilesEqual(profile, savedProfile)) {
          resolve({ isSaved: true, index: i, profile: savedProfile })

        }
      }

      resolve({ isSaved: false, index: -1, profile: null })
    })
  });
}

function profilesEqual(profile1, profile2) {
  return profile1.id === profile2.id
  /*
  const comparedFields = ["name", "jobTitle", "companyName", "imgSrc"]
  for (const field of comparedFields) {
    if (profile1.hasOwnProperty(field) !== profile2.hasOwnProperty(field)
      || profile1[field] !== profile2[field]) {
      return false;
    }
  }
  return true;
  */

}
async function getTags() {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(["tag_list_id"], async (res) => {
      const result = await queryChoiceListValues(res.tag_list_id);
      if (!result || result.hasOwnProperty("errors"))
        resolve([])
      else {
        let tags = result?.data.getFieldItems.map(field => field.name);
        resolve(tags);

      }
    });
  })
}
function closeToast() {
  const toast = document.getElementById('toast');
  if (toast)
    toast.remove();
};

function runToast(message, type) {
  let timeoutDuration = 3000;
  if (type === 'fail') {
    timeoutDuration = 15000;
  }
  const FRAME = document.getElementById('frame');
  if (!FRAME) return;
  const toast = ` 
  <div id="toast" class="toast  animate__fadeInDown animate__animated">
    <div class="toast_box ${type}">
      <p>
        ${message}
      </p>
      <i id="closeButtonToast" class="fas fa-times toast-close"></i>
    </div>
  </div>`;
  FRAME.insertAdjacentHTML('afterbegin', toast);
  const closeButtonToast = document.getElementById('closeButtonToast');
  closeButtonToast.addEventListener('click', closeToast);
  setTimeout(() => {
    closeToast()
  }, timeoutDuration);

}

function removeLoadingToButton(el) {
  el.removeAttribute('disabled');
  el.classList.remove('button-loading');
}
function setLoadingButton(el) {
  el.setAttribute('disabled', 'disabled');
  el.classList.add("button-loading")
}

function checkLogin() {
  chrome.storage.sync.get(['uid', 'access_token', 'refresh_token'], (res) => {
    if (res.uid === "" || res.access_token === "" || res.refresh_token === "") {
      window.location.replace('login.html');
    }
  });
}

function saveCurProfile(profile) {
  return new Promise((resolve) => {
    chrome.storage.sync.set({ curProfile: profile }, resolve)
  })
}

function getCurProfile() {
  return new Promise((resolve) => {
    chrome.storage.sync.get(['curProfile'], (res) => {
      resolve(res.curProfile)
    })
  })
}

function getFromStorage(key) {
  return new Promise((resolve) => {
    chrome.storage.sync.get([key], (res) => {
      resolve(res[key])
    })
  })

}
async function onFocusChange(newId, type) {
  if (type === "tab") {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (newId === tab.id && tab.url.includes("www.linkedin.com/sales")) {

      setOverlay('loading')
      chrome.tabs.sendMessage(newId, { action: "sendDetails" }, receiveDetails)
    }
  }
  else if (type === "window" && newId !== chrome.windows.WINDOW_ID_NONE) {
    const curWindow = await chrome.windows.getCurrent()
    if (curWindow.id === newId) {
      setOverlay('loading')
      let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      chrome.tabs.sendMessage(tab.id, { action: "sendDetails" }, receiveDetails)

    }
  }
}
function initFocusListeners() {
  chrome.windows.onFocusChanged.addListener(async (windowId) => {
    await onFocusChange(windowId, "window")
  })
  chrome.tabs.onActivated.addListener(async (activeInfo) => {
    await onFocusChange(activeInfo.tabId, "tab")
  })

  chrome.tabs.onUpdated.addListener(async function (tabId, changeInfo, tab) {
    if (tab.url && changeInfo.status == 'complete' && tab.active === true) {
      await onFocusChange(tabId, "tab")
    }
  });
}