import * as PDFJS from 'pdfjs-dist';

PDFJS.GlobalWorkerOptions.workerSrc = `./pdf.worker.min.js`;

export const PDF_MIME_TYPE = 'application/pdf';
export const PDF_EXTENSION = '.pdf';
export const IMAGE_MIME_TYPES = ['image/png', 'image/jpeg'];
export const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'];

export const IMAGE_SIZE_LIMIT = 5 * 1024 * 1024;

export function isImageFile(file: File) {
  return (
    IMAGE_MIME_TYPES.includes(file.type) &&
    IMAGE_EXTENSIONS.some((ext) => file.name.endsWith(ext))
  );
}

export function isPDFFile(file: File) {
  return file.type === PDF_MIME_TYPE && file.name.endsWith(PDF_EXTENSION);
}

export function isFileUnderLimit(file: File, limit: number = IMAGE_SIZE_LIMIT) {
  return file.size <= limit;
}

export async function pdf2Images(file: File): Promise<File[]> {
  const fileBuffer = await file.arrayBuffer();
  const pdf = await PDFJS.getDocument(fileBuffer).promise;
  const page = await pdf.getPage(1);
  const viewport = page.getViewport({ scale: 1 });
  const canvasContext = document.createElement('canvas').getContext('2d');
  canvasContext.canvas.width = viewport.width;
  canvasContext.canvas.height = viewport.height;

  await page.render({
    viewport,
    canvasContext,
  }).promise;

  const blob = await new Promise<Blob>((resolve) => {
    canvasContext.canvas.toBlob(resolve, 'image/png');
  });

  canvasContext.canvas.remove();
  return [new File([blob], file.name.replace('.pdf', '.png'))];
}
