import React from 'react';

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

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

const Thumbnails = () => {
  const [{pdf, totalPage, currentPage, navbarState, viewport}, dispatch] = useStore();
  const { switchNavbar } = useActions(dispatch);

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

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

    const renderContext = {
      canvasContext: context,
      viewport,
    };
    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={() => { switchNavbar(''); }}
      />
    )
  );
};

export default Thumbnails;
