import { logger } 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) => 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) {
            logger.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 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) };
}
//# sourceMappingURL=utils.js.map
