"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createImageNode = void 0;
exports.isImageNode = isImageNode;
exports.loadImage = loadImage;
exports.getImageSize = getImageSize;
exports.getImageSizeNew = getImageSizeNew;
const logger_1 = require("../../../logger.js");
const utils_1 = require("../../../utils/index.js");
const markdown_1 = require("../../markdown/index.js");
const specs_1 = require("../../specs.js");
const const_1 = require("./const.js");
function isImageNode(node) {
    return node.type.name === markdown_1.imageNodeName;
}
const createImageNode = (imgType, opts) => async ({ result, file }) => {
    const attrs = {
        [specs_1.ImgSizeAttr.Src]: result.url,
        [specs_1.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_1.logger.error(err);
        }
    }
    return imgType.create(attrs);
};
exports.createImageNode = createImageNode;
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);
    });
}
function getImageSize(img) {
    return { height: String(Math.min(const_1.IMG_MAX_HEIGHT, img.height)) };
}
function getImageSizeNew({ width, height }) {
    const size = (0, utils_1.getProportionalSize)({
        width,
        height,
        imgMaxHeight: const_1.IMG_MAX_HEIGHT,
    });
    return { width: String(size.width), height: String(size.height) };
}
//# sourceMappingURL=utils.js.map
