export function getCookie(name) {
  // Split cookie string and get all individual name=value pairs in an array
  var cookieArr = document.cookie.split(";");

  // Loop through the array elements
  for (var i = 0; i < cookieArr.length; i++) {
    var cookiePair = cookieArr[i].split("=");

    /* Removing whitespace at the beginning of the cookie name
          and compare it with the given string */
    if (name == cookiePair[0].trim()) {
      // Decode the cookie value and return
      return decodeURIComponent(cookiePair[1]);
    }
  }

  // Return null if not found
  return null;
}

export const getCookieAffiliate = () => {
  const cookies = document.cookie;
  const cookieArray = cookies.split(";");

  let affiliateAccount = null;

  cookieArray?.forEach((cookieValue) => {
    const cookie = cookieValue?.trim();
    if (cookie.startsWith("affiliateAccount=")) {
      affiliateAccount = cookie.substring(
        "affiliateAccount=".length,
        cookie.length
      );
    }
  });

  return affiliateAccount;
};

export const setCookie = (name, data) => {
  const date = new Date();
  date.setDate(date.getDate() + 20);
  const expires = "; expires=" + date.toUTCString();
  const path = "; path=/";
  const domain = window.location.href.includes("localhost")
    ? "localhost"
    : window.location.hostname?.includes("ca")
    ? ".learngual.ca"
    : ".learngual.com";
  document.cookie = `${name}=` + data + expires + path + "; domain=" + domain;
};
