import { Component, Element, Event, h, Prop, State, Watch } from '@stencil/core';
import pdf from 'pdfjs-dist/build/pdf';
// Works well with 2.12.313
pdf.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdf.version}/pdf.worker.min.js`;
export class AkordPdfViewer {
  constructor() {
    this.pdfZoom = 1;
    this.isDocumentLoading = false;
  }
  async componentWillLoad() {
    this.isDocumentLoading = true;
    // Refresh view while document is loading...
    this.pdfDocument = null;
    if (this.pdfDocumentLoader) {
      this.pdfDocumentLoader.cancel();
    }
    this.pdfDocumentLoader = pdf.getDocument(this.src);
    this.pdfDocument = await this.pdfDocumentLoader.promise;
    this.isDocumentLoading = false;
  }
  componentDidLoad() {
    const width = this.pdfContext.offsetWidth;
    const height = this.pdfContext.offsetHeight;
    this.pdfContext.setAttribute('style', `width: ${width}px`);
    this.pdfContext.style.width = `${width} px`;
    this.pdfContext.setAttribute('style', `height: ${height}px`);
    this.pdfContext.style.height = `${height} px`;
  }
  async updateSrc(newValue, oldValue) {
    if (newValue === oldValue) {
      return;
    }
    this.isDocumentLoading = true;
    // Refresh view while document is loading...
    this.pdfDocument = null;
    console.log("reload?");
    this.pdfDocument = await pdf.getDocument(newValue).promise;
    this.isDocumentLoading = false;
  }
  handleZoom(newZoom) {
    this.pdfZoom = newZoom;
  }
  handleMouseEnter() {
    var _a;
    (_a = this.btns) === null || _a === void 0 ? void 0 : _a.classList.add('active');
    clearTimeout(this.zoomButtonsHideTimeout);
  }
  handleMouseLeave() {
    this.zoomButtonsHideTimeout = setTimeout(() => { var _a; return (_a = this.btns) === null || _a === void 0 ? void 0 : _a.classList.remove('active'); }, 1000);
  }
  handleMouseMove() {
    this.handleMouseEnter();
    this.handleMouseLeave();
  }
  /** Page rotation in degrees */
  async renderPage(pageNum, canvas, rotation = 0) {
    const currentPage = await this.pdfDocument.getPage(pageNum);
    // Fit page on pdfContext width and then adjust zoom
    let viewport = currentPage.getViewport({ scale: 1, rotation });
    const scale = (this.pdfContext.offsetWidth - 50) / viewport.width; // margin for cards
    viewport = currentPage.getViewport({ scale: this.pdfZoom * scale, rotation });
    // Set canvas size
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    canvas.parentElement.setAttribute('style', `width:${canvas.width}px;height:${canvas.height}px`);
    canvas.parentElement.style.width = `${canvas.width}px`;
    canvas.parentElement.style.height = `${canvas.height}px`;
    // Render PDF page into canvas context
    const renderContext = {
      viewport,
      canvasContext: canvas.getContext('2d'),
    };
    // Wait for rendering to finish
    await currentPage.render(renderContext).promise;
    this.pageRendered.emit(pageNum);
  }
  renderPageCard(pageNum) {
    return h("ion-card", null,
      h("canvas", { key: pageNum, ref: r => this.renderPage(pageNum, r) }));
  }
  renderDocument() {
    if (this.pdfDocument && !this.isDocumentLoading) {
      return [...Array(this.pdfDocument.numPages).keys()].map(p => this.renderPageCard(p + 1));
    }
    return h("center", null,
      h("ion-spinner", { name: "dots" }));
  }
  renderButtons() {
    if (this.pdfDocument) {
      return h("ion-buttons", { ref: e => (this.btns = e), class: 'pdf-zoom-buttons active', onMouseEnter: () => this.handleMouseEnter(), onMouseLeave: () => this.handleMouseLeave() },
        h("ion-button", { onClick: () => this.handleZoom(this.pdfZoom - 0.1) },
          h("ion-icon", { slot: "icon-only", name: "remove-outline" })),
        h("ion-button", { onClick: () => this.handleZoom(1) },
          h("ion-icon", { slot: "icon-only", name: "refresh" })),
        h("ion-button", { onClick: () => this.handleZoom(this.pdfZoom + 0.1) },
          h("ion-icon", { slot: "icon-only", name: "add" })));
    }
    return null;
  }
  render() {
    return (h("div", { style: { height: this.height, display: 'block', textAlign: '-webkit-center' }, ref: e => (this.pdfContext = e), class: "pdf-context" },
      h("div", { class: "pdf-container", onMouseMove: () => this.handleMouseMove() }, this.renderDocument()),
      this.renderButtons()));
  }
  static get is() { return "akord-pdf-viewer"; }
  static get originalStyleUrls() { return {
    "$": ["akord-pdf-viewer.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["akord-pdf-viewer.css"]
  }; }
  static get properties() { return {
    "src": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "PDF document source"
      },
      "attribute": "src",
      "reflect": false
    },
    "height": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "height",
      "reflect": false
    }
  }; }
  static get states() { return {
    "pdfZoom": {},
    "pdfDocument": {},
    "pdfDocumentLoader": {}
  }; }
  static get events() { return [{
      "method": "pageRendered",
      "name": "pageRendered",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Emitted when a page has been rendered"
      },
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      }
    }]; }
  static get elementRef() { return "component"; }
  static get watchers() { return [{
      "propName": "src",
      "methodName": "updateSrc"
    }]; }
}
