// Copyright (c) 2017 PlanGrid, Inc.

import React from 'react';
import { Document, Page } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';

export default class ReactPDFDriver extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numPages: null,
      pageIdx: 0
    };

    this.onDocumentLoadSuccess = this.onDocumentLoadSuccess.bind(this);
    this.onNextPage = this.onNextPage.bind(this);
    this.onPreviousPage = this.onPreviousPage.bind(this);
  }

  onDocumentLoadSuccess(document) {
    const { numPages } = document;
    this.setState({
      numPages
    });
  }

  onNextPage() {
    const { pageIdx, numPages } = this.state;
    this.setState({
      pageIdx: pageIdx + 1 >= numPages - 1 ? numPages - 1 : pageIdx + 1
    });
  }

  onPreviousPage() {
    const { pageIdx } = this.state;
    this.setState({
      pageIdx: pageIdx - 1 < 0 ? 0 : pageIdx - 1
    });
  }

  render() {
    const { pageIdx } = this.state;
    return (
      <div className="file-viewer-wrapper">
        <div className="file-viewer">
          <Document
            file={this.props.filePath}
            renderMode={this.props.renderMode}
            width={800}
            onLoadSuccess={this.onDocumentLoadSuccess}
            onLoadError={e => console.log(e)}
          >
            {/* {Array.from(new Array(numPages), (el, index) => ( */}
            <Page
              key={`page_${pageIdx + 1}`}
              pageNumber={pageIdx + 1}
              id={pageIdx + 1}
              renderTextLayer
            />
            {/* ))} */}
          </Document>
        </div>
        <div style={{ position: 'absolute', width: '100%', margin: 0, top: '50%' }}>
          <button
            type="button"
            className={`nav-btn ${this.props.navClassname}`}
            onClick={this.onPreviousPage}
            style={{ left: '7px' }}
          />
          <button
            type="button"
            className={`nav-btn ${this.props.navClassname}`}
            onClick={this.onNextPage}
            style={{ right: '14px', transform: 'rotate(180deg)' }}
          />
        </div>
      </div>
    );
  }
}

ReactPDFDriver.defaultProps = {
  renderMode: 'canvas'
};
