import React from 'react';

import ThumbnailsComponent from '../components/ThumbnailViewer';

import useActions from '../actions';
import useStore from '../store';

const Thumbnails: React.FC = () => {
  const [
    { pdf, totalPage, currentPage, navbarState, viewport },
    dispatch,
  ] = useStore();
  const { setNavbar } = useActions(dispatch);

  const getPdfImage = async (pageNum: number): Promise<string> => {
    let dataUrl = '';

    if (pdf) {
      const page = await pdf.getPage(pageNum);
      const canvas = document.createElement('canvas');
      const context: CanvasRenderingContext2D = canvas.getContext(
        '2d',
      ) as CanvasRenderingContext2D;
      canvas.height = viewport.height;
      canvas.width = viewport.width;

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

      if (page) {
        const renderTask = page.render(renderContext);
        await renderTask.promise;
      }

      dataUrl = canvas.toDataURL();
      canvas.remove();
    }

    return dataUrl;
  };

  return (
    pdf && (
      <ThumbnailsComponent
        getPdfImage={getPdfImage}
        totalPage={totalPage}
        currentPage={currentPage}
        isActive={navbarState === 'thumbnails'}
        close={(): void => {
          setNavbar('');
        }}
      />
    )
  );
};

export default Thumbnails;
