"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const htmlUtils_1 = require("../../htmlUtils");
const utils = require("../../utils");
function renderImageHtml(before, src, after, ruleOptions) {
    const r = utils.imageReplacement(ruleOptions.ResourceModel, { src, before, after }, ruleOptions.resources, ruleOptions.resourceBaseUrl, ruleOptions.itemIdToUrl);
    if (typeof r === 'string')
        return r;
    if (r)
        return `<img ${before} ${(0, htmlUtils_1.attributesHtml)(r)} ${after}/>`;
    return `[Image: ${src}]`;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
function plugin(markdownIt, ruleOptions) {
    const Resource = ruleOptions.ResourceModel;
    const htmlBlockDefaultRender = markdownIt.renderer.rules.html_block ||
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
        function (tokens, idx, options, _env, self) {
            return self.renderToken(tokens, idx, options);
        };
    const htmlInlineDefaultRender = markdownIt.renderer.rules.html_inline ||
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
        function (tokens, idx, options, _env, self) {
            return self.renderToken(tokens, idx, options);
        };
    const imageRegex = /<img(.*?)src=["'](.*?)["'](.*?)>/gi;
    // eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
    const handleImageTags = function (defaultRender) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
        return function (tokens, idx, options, env, self) {
            const token = tokens[idx];
            const content = token.content;
            if (!content.match(imageRegex))
                return defaultRender(tokens, idx, options, env, self);
            // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
            return content.replace(imageRegex, (_v, before, src, after) => {
                if (!Resource.isResourceUrl(src))
                    return `<img${before}src="${src}"${after}>`;
                return renderImageHtml(before, src, after, ruleOptions);
            });
        };
    };
    // It seems images sometimes are inline, sometimes a block
    // to make sure they both render correctly.
    markdownIt.renderer.rules.html_block = handleImageTags(htmlBlockDefaultRender);
    markdownIt.renderer.rules.html_inline = handleImageTags(htmlInlineDefaultRender);
}
exports.default = { plugin };
//# sourceMappingURL=html_image.js.map