import { jsx as _jsx } from "react/jsx-runtime";
import { useUserSession } from "@vertesia/ui/session";
import React, { createContext, useEffect, useState } from "react";
const DEFAULT_PAGE_COUNT = 10;
const ADVANCED_PROCESSING_PREFIX = "magic-pdf";
class PageLayoutProvider {
    totalPages;
    layoutUrls = [];
    cache;
    constructor(totalPages) {
        this.totalPages = totalPages;
        this.cache = new Array(totalPages);
    }
    async loadUrls(vertesia, objectId) {
        const layoutPromises = [];
        for (let i = 0; i < this.totalPages; i++) {
            layoutPromises.push(getLayoutUrlForPage(vertesia, objectId, i + 1));
        }
        const layoutUrls = await Promise.all(layoutPromises);
        this.layoutUrls = layoutUrls.map((r) => r.url);
    }
    async getPageLayout(page) {
        const index = page - 1;
        let content = this.cache[index];
        if (content === undefined) {
            const url = this.layoutUrls[index];
            content = await fetch(url, { method: "GET" }).then((r) => {
                if (r.ok) {
                    return r.text();
                }
                else {
                    throw new Error("Failed to fetch json layout: " + r.statusText);
                }
            });
            this.cache[index] = content;
        }
        return content;
    }
}
class PageMarkdownProvider {
    totalPages;
    markdownUrls = [];
    cache;
    constructor(totalPages) {
        this.totalPages = totalPages;
        this.cache = new Array(totalPages);
    }
    async loadUrls(vertesia, objectId) {
        const markdownPromises = [];
        for (let i = 0; i < this.totalPages; i++) {
            markdownPromises.push(getMarkdownUrlForPage(vertesia, objectId, i + 1));
        }
        const markdownUrls = await Promise.all(markdownPromises);
        this.markdownUrls = markdownUrls.map((r) => r.url);
    }
    async getPageMarkdown(page) {
        const index = page - 1;
        let content = this.cache[index];
        if (content === undefined) {
            const url = this.markdownUrls[index];
            content = await fetch(url, { method: "GET" }).then((r) => {
                if (r.ok) {
                    return r.text();
                }
                else {
                    throw new Error("Failed to fetch markdown: " + r.statusText);
                }
            });
            this.cache[index] = content;
        }
        return content;
    }
}
const PdfPageContext = createContext(undefined);
export function PdfPageProvider({ children, object }) {
    const { client } = useUserSession();
    const [info, setInfo] = useState();
    useEffect(() => {
        const page_count = object.metadata.page_count ||
            DEFAULT_PAGE_COUNT;
        getPdfPagesInfo(client, object, page_count).then(setInfo);
    }, [object.id]);
    return (info && (_jsx(PdfPageContext.Provider, { value: info, children: children })));
}
function getBasePath(objectId) {
    return `${ADVANCED_PROCESSING_PREFIX}/${objectId}`;
}
function getPageImagePath(objectId, pageNumber, ext = ".jpg") {
    return `${getBasePath(objectId)}/pages/page-${pageNumber}${ext}`;
}
function getPageAnnotatedImagePath(objectId, pageNumber, ext = ".jpg") {
    return `${getBasePath(objectId)}/pages/page-${pageNumber}-annotated${ext}`;
}
function getPageInstrumentedImagePath(objectId, pageNumber, ext = ".jpg") {
    return `${getBasePath(objectId)}/pages/page-${pageNumber}.instrumented${ext}`;
}
function getPageOriginalImagePath(objectId, pageNumber, ext = ".jpg") {
    return `${getBasePath(objectId)}/pages/page-${pageNumber}.original${ext}`;
}
function getLayoutJsonPath(objectId, pageNumber) {
    return `${getBasePath(objectId)}/pages/page-${pageNumber}.layout.json`;
}
function getMarkdownPath(objectId, pageNumber) {
    return `${getBasePath(objectId)}/pages/page-${pageNumber}.md`;
}
export function getResourceUrl(vertesia, objectId, name) {
    return vertesia.files
        .getDownloadUrl(`${getBasePath(objectId)}/${name}`)
        .then((r) => r.url);
}
function getImageUrlForPage(vertesia, objectId, pageNumber) {
    return vertesia.files.getDownloadUrl(getPageImagePath(objectId, pageNumber));
}
function getAnnotatedImageUrlForPage(vertesia, objectId, pageNumber) {
    return vertesia.files.getDownloadUrl(getPageAnnotatedImagePath(objectId, pageNumber));
}
function getInstrumentedImageUrlForPage(vertesia, objectId, pageNumber) {
    return vertesia.files.getDownloadUrl(getPageInstrumentedImagePath(objectId, pageNumber));
}
function getOriginalImageUrlForPage(vertesia, objectId, pageNumber) {
    return vertesia.files.getDownloadUrl(getPageOriginalImagePath(objectId, pageNumber));
}
function getLayoutUrlForPage(vertesia, objectId, pageNumber) {
    return vertesia.files.getDownloadUrl(getLayoutJsonPath(objectId, pageNumber));
}
function getMarkdownUrlForPage(vertesia, objectId, pageNumber) {
    return vertesia.files.getDownloadUrl(getMarkdownPath(objectId, pageNumber));
}
async function getPdfPagesInfo(vertesia, object, page_count) {
    const imageUrlPromises = [];
    for (let i = 0; i < page_count; i++) {
        imageUrlPromises.push(getImageUrlForPage(vertesia, object.id, i + 1));
    }
    const imageUrls = await Promise.all(imageUrlPromises);
    const annotatedImageUrlPromises = [];
    for (let i = 0; i < page_count; i++) {
        annotatedImageUrlPromises.push(getAnnotatedImageUrlForPage(vertesia, object.id, i + 1));
    }
    const annotatedImageUrls = await Promise.all(annotatedImageUrlPromises);
    const instrumentedImageUrlPromises = [];
    for (let i = 0; i < page_count; i++) {
        instrumentedImageUrlPromises.push(getInstrumentedImageUrlForPage(vertesia, object.id, i + 1));
    }
    const instrumentedImageUrls = await Promise.all(instrumentedImageUrlPromises);
    const originalImageUrlPromises = [];
    for (let i = 0; i < page_count; i++) {
        originalImageUrlPromises.push(getOriginalImageUrlForPage(vertesia, object.id, i + 1));
    }
    const originalImageUrls = await Promise.all(originalImageUrlPromises);
    const layoutProvider = new PageLayoutProvider(page_count);
    await layoutProvider.loadUrls(vertesia, object.id);
    const markdownProvider = new PageMarkdownProvider(page_count);
    await markdownProvider.loadUrls(vertesia, object.id);
    const xml = object.text ? cleanXml(object.text) : "";
    return {
        count: page_count,
        urls: imageUrls.map((r) => r.url),
        originalUrls: originalImageUrls.map((r) => r.url),
        annotatedUrls: annotatedImageUrls.map((r) => r.url),
        instrumentedUrls: instrumentedImageUrls.map((r) => r.url),
        layoutProvider,
        markdownProvider,
        xml,
        xmlPages: object.text ? extractXmlPages(xml) : [],
    };
}
export function usePdfPagesInfo() {
    const context = React.useContext(PdfPageContext);
    if (!context) {
        throw new Error("usePdfPagesInfo must be used within a PdfPageProvider");
    }
    return context;
}
function extractXmlPages(xml) {
    // Parse the XML string
    const doc = new DOMParser().parseFromString(cleanXml(xml), "text/xml");
    const pages = doc.getElementsByTagName("page");
    const serializer = new XMLSerializer();
    return Array.from(pages).map((p) => serializer.serializeToString(p));
}
function cleanXml(xml) {
    const cleanedXML = xml
        // eslint-disable-next-line no-control-regex
        .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "")
        .replace(/<\?xml.*?\?>/g, "");
    return cleanedXML;
}
//# sourceMappingURL=PdfPageProvider.js.map