import React from 'react';

import Page from '../components/Page';
import Annotation from './Annotation';
import { getPdfPage } from '../helpers/pdf';

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

type Props = {
  index: number;
  renderingState: RenderingStateType;
};

const PdfPage: React.FC<Props> = ({ index, renderingState }: Props) => {
  const [
    { viewport, pdf, rotation, annotations, scale, watermark, currentPage },
    dispatch,
  ] = useStore();
  const { setTextDivs } = useActions(dispatch);

  const getAnnotationWithPage = (
    arr: AnnotationType[],
    pageNum: number
  ): React.ReactNode[] => {
    const result: React.ReactNode[] = [];

    arr.forEach((ele: AnnotationType, i: number) => {
      const page = ele.obj_attr ? ele.obj_attr.page + 1 : -1;

      if (page === pageNum) {
        result.push(
          <Annotation key={ele.id} scale={scale} index={i} {...ele} />
        );
      }
    });

    return result;
  };

  return (
    <Page
      pageNum={index}
      renderingState={renderingState}
      viewport={viewport}
      scale={scale}
      getPage={(): Promise<any> => getPdfPage(pdf, index)}
      rotation={rotation}
      watermark={watermark}
      annotations={getAnnotationWithPage(annotations, index)}
      setTextDivs={setTextDivs}
      currentPage={currentPage}
    />
  );
};

export default PdfPage;
