import { getDictionary } from "@/dictionaries";
import { fileTypeMap } from "@/models/FileTypeMap";
import { getCpanelVars } from "@/models/cpanel";
import { clsx, type ClassValue } from "clsx";
import dayjs from "dayjs";
import { twMerge } from "tailwind-merge";
import { getLocale } from "./locales";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function convertBytes(bytes: number): string {
  const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  let i = 0;
  while (bytes >= 1024 && i < units.length - 1) {
    bytes /= 1024;
    i++;
  }
  return `${bytes.toFixed(2)} ${units[i]}`;
}

export function getExtension(fileName: string): string {
  const parts = fileName.split(".");

  return parts.length > 1 ? parts[parts.length - 1] : "";
}

export function identifyFileType(
  fileName?: string,
  analyzeContent = false,
): string {
  if (!fileName) return "";

  const extension = getExtension(fileName);

  if (fileTypeMap.hasOwnProperty(extension)) {
    return fileTypeMap[extension];
  }

  return extension;
}

export async function cpanelFetch(
  command: string,
  method?: "POST",
  body?: FormData,
) {
  const dict = await getDictionary(getLocale());
  const cpanel = getCpanelVars();

  const response = await fetch(`${cpanel.fetch}${command}`, {
    method,
    body,
    headers: {
      Authorization: `cpanel ${cpanel.user}:${cpanel.token}`,
    },
    cache: "no-cache",
  });

  if (!response.ok) {
    throw new Error(dict.alerts.general.connection_fail, {
      cause: "cpanel_error",
    });
  }

  return response;
}

export async function showDeviceNotification(
  text: string,
  options?: NotificationOptions,
) {
  if (!("Notification" in window)) {
    console.log("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    const notification = new Notification(text, options);
  } else if (Notification.permission !== "denied") {
    Notification.requestPermission().then((permission) => {
      if (permission === "granted") {
        const notification = new Notification(text);
      }
    });
  }
  return;
}

export function codeGenerator(
  length: number,
  min: number = 0,
  max: number = 9,
) {
  const numbers = new Array(max - min + 1);
  for (let i = min; i <= max; i++) {
    numbers[i - min] = i;
  }

  const numerosAleatorios = numbers.sort(() => Math.random() - 0.5);
  const codigo = numerosAleatorios.slice(0, length).join("");

  return codigo;
}

/**
 * @deprecated use `ConvertResultQueryToJSON` instead
 * @param obj 
 * @returns 
 */
export const convertKeysToLowercase = (obj) => {
  return Object.keys(obj).reduce((acc, key) => {
    acc[key.toLowerCase()] = obj[key];
    return acc;
  }, {});
};

export const LocaleDate = (date: any, locale: string)  => {
  const formats = {
    long: {
      en: "MMMM DD, YYYY",
      es: "DD [de] MMMM [de] YYYY",
    }
  }

  const long = () => {
    return dayjs(date).locale(locale).format(formats.long[locale]);
  }

  return {
    long
  }
}