const pdfjsLib = await import('./pdf/pdf.mjs');
const pdfjsWorker = await import('./pdf/pdf.worker.mjs');

// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;


export function displayPdf(options) {
  var pdfDoc = null,
      pageNum = 1,
      pageRendering = false,
      pageNumPending = null,
      ctx = options.canvas.getContext('2d');

  /**
   * Get page info from document, resize canvas accordingly, and render page.
   * @param num Page number.
   */
  function renderPage(num) {
    pageRendering = true;
    // Using promise to fetch the page
    pdfDoc.getPage(num).then(function(page) {
      var canvasWidth = options.canvas.getBoundingClientRect().width,
          pageWidth = page.getViewport({scale: 1.0}).width,
          scale = canvasWidth/pageWidth,
          viewport = page.getViewport({scale: scale});
      options.canvas.height = viewport.height;
      options.canvas.width = viewport.width;

      // Render PDF page into canvas context
      var renderContext = {
        canvasContext: ctx,
        viewport: viewport
      };
      var renderTask = page.render(renderContext);

      // Wait for rendering to finish
      renderTask.promise.then(function() {
        pageRendering = false;
        if (pageNumPending !== null) {
          // New page rendering is pending
          renderPage(pageNumPending);
          pageNumPending = null;
        }
      });
    });

    // Update page counters
    options.pageNum.textContent = num;
  }

  /**
   * If another page rendering in progress, waits until the rendering is
   * finised. Otherwise, executes rendering immediately.
   */
  function queueRenderPage(num) {
    if (pageRendering) {
      pageNumPending = num;
    } else {
      renderPage(num);
    }
  }

  /**
   * Re-render page (e.g. on resize)
   */
  function reRender() {
      queueRenderPage(pageNum);
  }
  document.defaultView.addEventListener('resize', reRender)

  /**
   * Displays previous page.
   */
  function onPrevPage() {
    if (pageNum <= 1) {
      return;
    }
    pageNum--;
    queueRenderPage(pageNum);
  }
  options.prevPage.addEventListener('click', onPrevPage);

  /**
   * Displays next page.
   */
  function onNextPage() {
    if (pageNum >= pdfDoc.numPages) {
      return;
    }
    pageNum++;
    queueRenderPage(pageNum);
  }
  options.nextPage.addEventListener('click', onNextPage);

  /**
   * Asynchronously downloads PDF.
   */
  pdfjsLib.getDocument(options.url).promise.then(function(pdfDoc_) {
    pdfDoc = pdfDoc_;
    options.pageCount.textContent = pdfDoc.numPages;

    // Initial/first page rendering
    renderPage(pageNum);
  });
}
