import { Component, Element, Event, h, Method, Prop, State, Watch } from '@stencil/core';
import pdf from 'pdfjs-dist/build/pdf';
pdf.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.worker.min.js';
export class AkordPdfViewerSpa {
  constructor() {
    this.pageNum = 1; // hardcoded to start at the page 1
    this.pageNumPending = null;
    this.scale = 0.9; // hardcoded to scale the document to full canvas size
    /**
     * Rotate the PDF in degrees
     * {number}
     */
    this.rotation = 0;
    this.darkMode = false;
  }
  /**
   * Listen for changes to src
   * @param newValue
   * @param oldValue
   */
  doSrc(newValue, oldValue) {
    if (newValue === oldValue) {
      return;
    }
    this.loadAndRender(newValue);
  }
  /**
   * Page forward
   * {MouseEvent} e
   */
  async pageNext(e) {
    e.preventDefault();
    if (this.pageNum >= this.pdfDocument.numPages) {
      return;
    }
    this.pageNum += 1;
    this.queueRenderPage(this.pageNum);
    this.handleMouseEnter();
  }
  /**
   * Page backward
   * e
   */
  async pagePrev(e) {
    e.preventDefault();
    if (this.pageNum <= 1) {
      return;
    }
    this.pageNum -= 1;
    this.queueRenderPage(this.pageNum);
    this.handleMouseEnter();
  }
  /**
   * Render the page based on pageNumber
   * {number} pageNumber
   */
  renderPage(pageNumber) {
    this.isPageRendering = true;
    this.pdfDocument
      .getPage(pageNumber)
      .then((page) => {
      const viewport = page.getViewport({ scale: this.scale, rotation: this.rotation });
      this.canvas.height = viewport.height;
      this.canvas.width = viewport.width;
      // Render PDF page into canvas context
      const renderContext = {
        viewport,
        canvasContext: this.ctx
      };
      // Render page method
      const renderTask = page.render(renderContext);
      // Wait for rendering to finish
      renderTask.promise
        .then(() => {
        this.isPageRendering = false;
        this.pageRendered.emit(this.pageNum);
        if (this.pageNumPending !== null) {
          this.renderPage(this.pageNumPending); // New page rendering is pending
          this.pageChange.emit(this.pageNumPending); // emit
          this.pageNumPending = null;
        }
      });
    });
  }
  queueRenderPage(pageNumber) {
    if (this.isPageRendering) {
      this.pageNumPending = pageNumber;
    }
    else {
      this.renderPage(pageNumber);
    }
  }
  componentDidLoad() {
    this.ctx = this.canvas.getContext('2d');
    if (this.src) {
      this.loadAndRender(this.src);
    }
  }
  loadAndRender(src) {
    pdf
      .getDocument(src).promise
      .then((pdfDocument) => {
      this.pdfDocument = pdfDocument;
      this.renderPage(this.pageNum);
    });
  }
  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();
  }
  render() {
    var _a;
    return (h("div", { class: this.containerClass, style: { height: `${this.height}px` }, onMouseMove: () => this.handleMouseMove() },
      h("canvas", { ref: e => this.canvas = e, class: this.darkMode ? 'dark-mode' : 'light-mode' }),
      h("ion-buttons", { ref: e => (this.btns = e), class: 'pdf-nav-buttons', onMouseEnter: () => this.handleMouseEnter(), onMouseLeave: () => this.handleMouseLeave() },
        h("ion-button", { class: "events-prevent", disabled: this.pageNum === 1, fill: "clear", size: "small", onClick: this.pagePrev.bind(this) },
          h("ion-icon", { slot: "icon-only", src: '/assets/arrow_left.svg' })),
        h("ion-button", { class: "events-prevent", disabled: this.pageNum === ((_a = this.pdfDocument) === null || _a === void 0 ? void 0 : _a.numPages), fill: "clear", size: "small", onClick: this.pageNext.bind(this) },
          h("ion-icon", { slot: "icon-only", src: '/assets/arrow_right.svg' })))));
  }
  static get is() { return "akord-pdf-viewer-spa"; }
  static get originalStyleUrls() { return {
    "$": ["akord-pdf-viewer-spa.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["akord-pdf-viewer-spa.css"]
  }; }
  static get properties() { return {
    "rotation": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "0 | 90 | 180 | 270 | 360",
        "resolved": "0 | 180 | 270 | 360 | 90",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Rotate the PDF in degrees\n{number}"
      },
      "attribute": "rotation",
      "reflect": false,
      "defaultValue": "0"
    },
    "height": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "height",
      "reflect": false
    },
    "width": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "width",
      "reflect": false
    },
    "src": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Src of the PDF to load and render\n{number}"
      },
      "attribute": "src",
      "reflect": false
    },
    "containerClass": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Container class name\n{string}"
      },
      "attribute": "container-class",
      "reflect": false
    },
    "darkMode": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "dark-mode",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "pageNum": {}
  }; }
  static get events() { return [{
      "method": "pageRendered",
      "name": "pageRendered",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      }
    }, {
      "method": "pageChange",
      "name": "pageChange",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      }
    }]; }
  static get methods() { return {
    "pageNext": {
      "complexType": {
        "signature": "(e: MouseEvent) => Promise<void>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "MouseEvent": {
            "location": "global"
          }
        },
        "return": "Promise<void>"
      },
      "docs": {
        "text": "Page forward\n{MouseEvent} e",
        "tags": []
      }
    },
    "pagePrev": {
      "complexType": {
        "signature": "(e: MouseEvent) => Promise<void>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "MouseEvent": {
            "location": "global"
          }
        },
        "return": "Promise<void>"
      },
      "docs": {
        "text": "Page backward\ne",
        "tags": []
      }
    }
  }; }
  static get elementRef() { return "component"; }
  static get watchers() { return [{
      "propName": "src",
      "methodName": "doSrc"
    }]; }
}
