import {getDocument, GlobalWorkerOptions, type PDFDocumentProxy} from "pdfjs-dist";
import type {RenderParameters} from "pdfjs-dist/types/src/display/api";

export default class Document {

    doc: Promise<PDFDocumentProxy>;
    constructor(bytesB64: string) {
        GlobalWorkerOptions.workerSrc = new URL('/pdf.worker.min.mjs', import.meta.url).toString();
        let loadingTask = getDocument({ data: atob(bytesB64) });
        this.doc = loadingTask.promise
    }

    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: RenderParameters = {
            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
    }

}