export const timeOut = (t: number) =>
  new Promise<void>((resolve) => {
    setTimeout(() => {
      resolve();
    }, t);
  });
export const setDynamicColumnHeight = async (selector: string) => {
  try {
    await timeOut(150);
    let count = 0;
    const array = Array.from(document.querySelectorAll(selector)) as HTMLElement[];
    const arrayRow: HTMLElement[][] = [[]];
    array.forEach((elem: HTMLElement, i: number, arr: HTMLElement[]) => {
      if (i && elem.offsetTop !== arr[i - 1].offsetTop) {
        arrayRow.push([]);
        count++;
      }
      arrayRow[count].push(elem);
    });
    arrayRow.forEach((arr) => {
      let maxHeight = 0;
      arr.forEach((elem: HTMLElement) => {
        elem.style.height = "auto";
        maxHeight = 0;
      });
      maxHeight = arr
        .map((elem: HTMLElement) => elem.clientHeight)
        .reduce((acc: number, val: number) => {
          if (acc > val) return acc;
          else return val;
        }, 0);
      arr.forEach((elem: HTMLElement) => (elem.style.height = maxHeight + "px"));
    });
  } catch (error) {
    console.dir(error);
  }
};
export const priceFormatter = (price: number) => {
  if (!price) return "$56.60";
  const formatter = new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP" });
  const formatterPrice = formatter.format(price);
  return formatterPrice;
};
export const generateRut = (v: string) => {
  let value = v.replace(/\D/g, "");
  if (value.length > 9) value = value.slice(0, 9);
  let numericPart = value.slice(0, -1);
  const lastDigit = value.slice(-1);

  numericPart =
    numericPart.length > 0
      ? new Intl.NumberFormat("es-CL", { maximumFractionDigits: 0 }).format(Number(numericPart))
      : "";

  value = numericPart.length > 0 ? `${numericPart}-${lastDigit}` : lastDigit;
  return value;
};

export const dateFormatter = (date: string) => {
  const formatterDate = date.split("-");
  return `${formatterDate[2]}/${formatterDate[1]}/${formatterDate[0]}`;
};
export const createCookie = (cookieName: string, value: string, timeInDays: number) => {
  if (typeof document !== "undefined") {
    const fecha = new Date();
    fecha.setTime(fecha.getTime() + timeInDays * 24 * 60 * 60 * 1000);
    const expiracion = "expires=" + fecha.toUTCString();
    document.cookie = cookieName + "=" + value + ";" + expiracion + ";path=/";
  }
};
export const checkCookie = (cookieName: string) => {
  if (typeof document !== "undefined") {
    const cookies = document.cookie.split(";");
    for (let cookie of cookies) {
      cookie = cookie.trim();
      if (cookie.startsWith(cookieName + "=")) return true;
    }
    return false;
  }
};
export const getPropertyFromText = (texto: string, key: string) => {
  if (key === "SHORTCODE") {
    const trimText = texto.replace('}{"RESPONSE":', ',"RESPONSE":');
    const jsonObject = JSON.parse(trimText);
    return jsonObject;
  } else {
    const regex = new RegExp(`"${key}":"(.*?)"`, "i");
    const match = texto.match(regex);
    if (match) {
      const token = match[1];
      return token;
    } else {
      return null;
    }
  }
};

export const getScript = (text: string) => {
  const regex = /"JSSTRING":"(.*?)","MESSAGE":/;
  const match = text.match(regex);

  if (match) {
    const extractedContent = match[1];
    console.log(extractedContent);
    return extractedContent;
  } else return null;
};

export const createScript = (content: string) => {
  try {
    if (typeof document === "undefined") return;
    const scriptElement = document.createElement("script");
    scriptElement.type = "text/javascript";
    scriptElement.innerHTML = content;
    const footer = document.querySelector("footer")!;
    if (footer) footer.appendChild(scriptElement);
  } catch (error) {
    console.log(error);
  }
};
