"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
postscriptum.plugin('ps-pdfjs', (processor, options) => {
    const { util } = postscriptum;
    const { io } = util;
    // Gestion de la largeur des lignes du canvas :
    // ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
    const pdfjsBaseUrl = '//cdn.jsdelivr.net/npm/pdfjs-dist@2.1.266/';
    let pdfjsLib;
    function importPdfJs() {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = `${pdfjsBaseUrl}/build/pdf.js`;
            script.addEventListener('error', () => {
                reject(new Error("Unable to load the pdf.js script."));
            });
            script.addEventListener('load', async () => {
                if ('exports' in window)
                    pdfjsLib = window['exports']['pdfjs-dist/build/pdf'];
                else
                    pdfjsLib = window.pdfjsLib;
                pdfjsLib.GlobalWorkerOptions.workerSrc = `${pdfjsBaseUrl}/build/pdf.worker.js`;
                resolve();
            });
            document.head.appendChild(script);
        });
    }
    const stylesheet = /* language=CSS */ `
	  ps-pdfjs-doc {
		  display: block;
	  }

	  ps-pdfjs-doc > * {
		  display: block;
	  }
	`;
    postscriptum.css.insertStyleSheet(processor.doc, stylesheet, true, 'ps-pdfjs');
    processor.on('pagination-start', async () => {
        const pdfElts = processor.source.querySelectorAll('ps-pdfjs-doc, ps-pdfjs-page');
        if (!pdfElts.length)
            return;
        await importPdfJs();
        if (!('map' in Promise))
            await io.loadScript("https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js");
        const serializer = new XMLSerializer();
        const renderings = [];
        return Promise.map(pdfElts, (pdfElt) => (async () => {
            try {
                const pdf = await pdfjsLib.getDocument({
                    url: pdfElt.getAttribute('src'),
                    cMapUrl: `${pdfjsBaseUrl}/cmaps`,
                    cMapPacked: true,
                });
                let start, end;
                if (pdfElt.hasAttribute('page')) {
                    start = end = parseInt(pdfElt.getAttribute('page'));
                }
                else if (pdfElt.localName == "ps-pdfjs-page") {
                    start = 1;
                    end = 1;
                }
                else {
                    start = 1;
                    end = pdf.numPages;
                }
                const renderer = pdfElt.hasAttribute('renderer') ? pdfElt.getAttribute('renderer') : options.renderer;
                for (let pageNum = start; pageNum <= end; pageNum++) {
                    const page = await pdf.getPage(pageNum);
                    const viewport = page.getViewport(options.dpi / 96);
                    if (renderer == 'svg') {
                        const opList = await page.getOperatorList();
                        const svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs);
                        svgGfx.embedFonts = true;
                        const svg = await svgGfx.getSVG(opList, viewport);
                        pdfElt.appendChild(svg);
                        /*const svgBlob = new Blob([serializer.serializeToString(svg)], { type: "image/svg+xml"});
                        const img = document.createElement('img');
                        img.src = URL.createObjectURL(svgBlob);
                        pdfElt.appendChild(img);*/
                    }
                    else {
                        const canvas = document.createElement('canvas');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;
                        const renderContext = {
                            canvasContext: canvas.getContext('2d'),
                            viewport: viewport
                        };
                        page.render(renderContext);
                        pdfElt.appendChild(canvas);
                    }
                }
                pdf.destroy();
            }
            catch (e) {
                const event = new CustomEvent('error', { detail: { message: e.message } });
                pdfElt.dispatchEvent(event);
                console.error(e);
            }
        })(), { concurrency: 4 });
    });
}, { renderer: 'svg', dpi: 300 });
