import * as React from "react";

import PDF from "pdfjs-dist";
import { File } from "../../Models";
import { FileService } from "../../Services";

class PdfThumbnail extends React.Component<any, any> {
  private _fileService: FileService = new FileService();

  constructor(props: any) {
    super(props);
    this.state = { pdf: "" };
    this.getPdf(this.props.pdf);
  }
  private makePDFThumb(page: any) {
    // draw page to fit into 96x96 canvas
    // debugger;
    let vp = page.getViewport(1);
    let canvas = document.createElement("canvas");
    canvas.width =115;
     canvas.height = 155;
    let scale = Math.min(canvas.width / vp.width, canvas.height / vp.height);

    return page
      .render({
        canvasContext: canvas.getContext("2d"),
        viewport: page.getViewport(scale)
      })
      .promise.then(function() {
        return canvas;
      });
  }

  private getPdf(pdf: any) {
    //   let fReader = new FileReader();
    //   let newFile;
    //   if (pdf && pdf.contentType.match('application/pdf.*')) {
    //   fReader.readAsDataURL(pdf);
    //     fReader.onloadend = function(event){
    //       if(event.target){
    //         debugger;
    //         newFile = event.target;
    //       }
    //     }
    //   }
    if (!pdf) {
      return;
    } else {
      let _this = this;

      let file = new File();

      file.path = pdf.path;

      let fullPath = this._fileService.getFullPath(file);

      PDF.getDocument(fullPath)
        .promise.then(function(doc: any) {
          //debugger;
          let pages = [1];
          // while (pages.length < doc.numPages) pages.push(pages.length + 1);
          return Promise.all(
            pages.map(function(num) {
              // create a div for each page and build a small canvas for it
              //   let div = document.createElement("div");
              return doc
                .getPage(num)
                .then(_this.makePDFThumb)
                .then(function(canvas: any) {
                  //debugger;
                  _this.setState({
                    pdfThumbnail: canvas
                  });
                  _this.setState({
                    pdfThumbnailSrc: canvas.toDataURL()
                  });
                });
            })
          );
        })
        .catch(console.error);
    }
  }

  render() {
    //debugger;
    return <div><img className="pdf-thumbnail-img" src={this.state.pdfThumbnailSrc}/></div>;
  }
}

export default PdfThumbnail;
