import {getDocument, type PDFDocumentProxy, GlobalWorkerOptions} from "pdfjs-dist";

export default class Document {

    doc: Promise<PDFDocumentProxy>;
    constructor(bytesB64: string) {
        console.log("Initializing pdf worker")
        GlobalWorkerOptions.workerSrc = '/dist/build/pdf.worker.min.mjs';
        let loadingTask = getDocument({ data: atob(bytesB64) });
        this.doc = loadingTask.promise;
        this.doc.then(d => d.getPrimitiveByPath("Trailer").then(a => console.log(a)))
    }

    public async render_page(num: number, canvas: HTMLCanvasElement) {
        let doc = await this.doc;
        let page = await doc.getPage(num);
        const outputScale = window.devicePixelRatio || 1;
        const scale = 1.5;
        let viewport = page.getViewport({ scale: scale, });
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        canvas.style.width = Math.floor(canvas.width) + "px";
        canvas.style.height =  Math.floor(canvas.height) + "px";
        const context = canvas.getContext("2d");
        if (!context) return "";
        const transform =  [1, 0, 0, 1, 0, 0];
        // viewport = page.getViewport({ scale: 0.7, offsetX: canvas.width / 4, offsetY: canvas.height / 4});

        const renderContext = {
            canvasContext: context,
            transform: transform,
            viewport: viewport,
        };
        let renderTask = page.render(renderContext);
        context.fillStyle = '#ffffff';
        context.fillRect(viewport.offsetX, viewport.offsetY, viewport.width, viewport.height);
        await renderTask.promise
    }

}