import { globalLogger } from "../../../logger.js";
import { getProportionalSize } from "../../../utils/index.js";
import { imageNodeName } from "../../markdown/index.js";
import { ImgSizeAttr } from "../../specs.js";
import { IMG_MAX_HEIGHT } from "./const.js";
export function isImageNode(node) {
    return node.type.name === imageNodeName;
}
export const createImageNode = (imgType, opts, logger) => async ({ result, file }) => {
    const attrs = {
        [ImgSizeAttr.Src]: result.url,
        [ImgSizeAttr.Alt]: result.name ?? file.name,
    };
    if (opts.needDimensions) {
        try {
            const sizes = await loadImage(file).then(opts.enableNewImageSizeCalculation ? getImageSizeNew : getImageSize);
            Object.assign(attrs, sizes);
        }
        catch (err) {
            globalLogger.error(err);
            logger.error({ error: err });
        }
    }
    return imgType.create(attrs);
};
export async function loadImage(imgFile) {
    return new Promise((resolve, reject) => {
        const img = document.createElement('img');
        img.src = URL.createObjectURL(imgFile);
        img.onload = () => {
            URL.revokeObjectURL(img.src);
            resolve(img);
        };
        img.onerror = (_e, _s, _l, _c, error) => reject(error);
    });
}
export async function loadImageFromUrl(url) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = (_e, _s, _l, _c, error) => reject(error);
        img.src = url;
    });
}
export function getImageSize(img) {
    return { height: String(Math.min(IMG_MAX_HEIGHT, img.height)) };
}
export function getImageSizeNew({ width, height }) {
    const size = getProportionalSize({
        width,
        height,
        imgMaxHeight: IMG_MAX_HEIGHT,
    });
    return { width: String(size.width), height: String(size.height) };
}
export function checkSvg(imageUrl) {
    return imageUrl && (/\.svg($|\?|#)/i.test(imageUrl) || imageUrl.startsWith('data:image/svg'));
}
export function findImageNode(doc, id) {
    let result = null;
    doc.descendants((node, pos) => {
        if (isImageNode(node) && node.attrs.id === id) {
            result = { node, pos };
            return false;
        }
        return true;
    });
    return result;
}
//# sourceMappingURL=utils.js.map
