// @ts-ignore
import pdfjs from 'pdfjs-dist';
// @ts-ignore
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
import { ProgressType, ViewportType } from '../constants/type';
import { objIsEmpty } from './utility';

const CMAP_URL = '../../node_modules/pdfjs-dist/cmaps/';
const CMAP_PACKED = true;

pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

export const fetchPdf = async (src: string, cb: (progress: ProgressType) => void) => {
  const loadingTask = pdfjs.getDocument({
    url: src,
    cMapUrl: CMAP_URL,
    cMapPacked: CMAP_PACKED,
  });

  if (cb) {
    loadingTask.onProgress = (progress: ProgressType) => {
      cb(progress);
    };
  }

  const pdf = await loadingTask.promise;
  return pdf;
};

export const renderPdfPage = async ({
  rootEle,
  page,
  viewport,
}: {
  rootEle: HTMLDivElement;
  page: any;
  viewport: ViewportType;
}) => {
  if (rootEle) {
    const canvas: HTMLCanvasElement = rootEle.querySelectorAll('canvas')[0] as HTMLCanvasElement;

    if (canvas) {
      const context: CanvasRenderingContext2D = canvas.getContext('2d')!;
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      const renderContext = {
        canvasContext: context,
        viewport,
      };

      if (!objIsEmpty(page)) {
        const renderTask = page.render(renderContext);

        await renderTask.promise;
      }
    }
  }
};
