import { filesize } from "filesize";

/**
 * Select a file to upload
 */
export async function selectFileToUpload(p: {
  allowedTypes: string[];
  maxSize?: number;
}): Promise<Blob | null> {
  // Create file element
  const fileEl = document.createElement("input");
  fileEl.type = "file";
  if (p.allowedTypes) fileEl.accept = p.allowedTypes.join(",");
  fileEl.click();

  // Wait for a file to be chosen
  await new Promise((res, _rej) =>
    fileEl.addEventListener("change", () => res(null))
  );

  if ((fileEl.files?.length ?? 0) === 0) return null;
  const file = fileEl.files![0];

  // Check file size
  if (p.maxSize && file.size > p.maxSize) {
    throw new Error(
      `Le fichier sélectionné est trop lourd ! (taille maximale acceptée : ${filesize(
        p.maxSize
      )})`
    );
  }

  return file;
}

export async function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = url;
  link.target = "_blank";
  link.rel = "noopener";
  link.download = filename;
  link.click();
}
