import React, { useEffect, useState, useRef } from 'react';
// @ts-ignore
import pdfjs, { AnnotationLayer } from 'pdfjs-dist';
// @ts-ignore
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';

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

pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

type Props = {
  src: string;
};

type PropsProgress = {
  loaded: number;
  total: number
}

const PdfComponent: React.FunctionComponent<Props> = ({
  src,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const annotationRef = useRef<HTMLDivElement>(null);
  const [viewportState, setViewport] = useState({width: 0, height: 0});

  const fetchPdf = async () => {
    const loadingTask = pdfjs.getDocument({
      url: src,
      cMapUrl: CMAP_URL,
      cMapPacked: CMAP_PACKED,
    });

    loadingTask.onProgress = (progress: PropsProgress) => {
      console.log(progress);
    };

    const pdf = await loadingTask.promise;

    const totalNum = pdf.numPages;
    console.log(totalNum);

    const firstPageNumber = 1;
    const page = await pdf.getPage(firstPageNumber);

    const scale = 1;
    const viewport = page.getViewport({ scale });
    setViewport(viewport);

    const canvas = canvasRef.current;
    let emptyCanvas: HTMLCanvasElement = document.createElement("canvas");
    let context: CanvasRenderingContext2D = emptyCanvas.getContext('2d')!;
    if (canvas) {
      context = canvas.getContext('2d')!;
      canvas.height = viewport.height;
      canvas.width = viewport.width;
    }

    // Render PDF page into canvas context
    const renderContext = {
      canvasContext: context,
      viewport,
    };
    const renderTask = page.render(renderContext);

    await renderTask.promise;

    page.getAnnotations({ intent: 'display' }).then((annotations : []) => {
      console.log(annotations);
      AnnotationLayer.update({
        viewport: viewport.clone({ dontFlip: true, }),
        annotations,
        div: annotationRef.current,
        page,
      });
    })
  };

  useEffect(() => {
    fetchPdf();
  }, []);

  return (
    <>
      <canvas
        ref={canvasRef}
        width={viewportState.width}
        height={viewportState.height}
      />
      <div ref={annotationRef} />
    </>
  );
};

export default PdfComponent;
