const PDFJS = require("pdfjs-dist");
const readFileData = (file) => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    resolve(e.target.result);
  };
  reader.onerror = (err) => {
    reject(err);
  };
  reader.readAsDataURL(file);
});
//function to convert first page of pdf to image for the thumbnail preview
export const convertPdfToImages = async (file) => {
  const data = await readFileData(file);
  const encoderQuality = 0.1;
  return PDFJS.getDocument(data)
  .then(async function (pdf) {
    const numberOfPages = pdf.numPages;
    const canvas = document.createElement("canvas");
    //fetch first page from pdf
    const page = await pdf.getPage(1);
    const viewport = page.getViewport({ scale: 1 });
    const context = canvas.getContext("2d");
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    await page.render({ canvasContext: context, viewport: viewport }).promise;
    //return the base64 format image that we use for preview
    const image = (canvas.toDataURL('image/jpeg', encoderQuality));
    canvas.remove();
    return Promise.resolve({image, numberOfPages});
  })
  .catch((error) => Promise.reject(error));
};
