"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanupHiddenCharacters = exports.cleanupImageText = exports.normalizePlainPart = void 0;
// this is a Node module. require is a must to work across different envs
const URL = require("url-parse");
const utils_1 = require("../utils");
const defaultOptions = {
    normalizeImagePlain: true,
};
const normalizePlainPart = (text, options) => {
    options = options
        ? Object.assign(defaultOptions, Object.assign({}, options))
        : defaultOptions;
    text = exports.cleanupHiddenCharacters(text);
    text = patchOutlookSafelinksWrappers(text);
    if (options === null || options === void 0 ? void 0 : options.sealUrl) {
        text = removeSeal(text, options.sealUrl);
    }
    if (options === null || options === void 0 ? void 0 : options.normalizeImagePlain) {
        text = exports.cleanupImageText(text);
    }
    text = utils_1.normalizeTextSpacings(text);
    return text.trim();
};
exports.normalizePlainPart = normalizePlainPart;
const patchOutlookSafelinksWrappers = (text) => {
    const links = text.match(/<https:.+?(safelinks\.protection\.outlook\.com).+?>/g);
    if (links) {
        links.forEach((link) => {
            const url = new URL(link.slice(1, link.length - 1), true);
            const originalUrl = url.query["url"];
            text = text.replace(link, `<${originalUrl}>`);
        });
    }
    return text;
};
/**
 * Function removes seal from the plain text.
 * @param plain
 * @param sealUrl
 */
const removeSeal = (plain, sealUrl) => {
    // For cases [<image-alt>]<<seal-url>>
    const sealRegex = `\\[.+?]\\s*<${sealUrl}>`;
    // For cases <<seal-url>>[<image-alt>]
    const sealRegexReversed = `<${sealUrl}>\\s*\\[.+?]`;
    return plain
        .replace(new RegExp(sealRegex), "")
        .replace(new RegExp(sealRegexReversed), "");
};
const cleanupImageText = (plain) => {
    // For cases [image: IMAGE_NAME.EXTENSION]
    const sealRegex = `\\[(image:\\s)(.*)\\]`;
    return plain.replace(new RegExp(sealRegex), "[$2]");
};
exports.cleanupImageText = cleanupImageText;
const cleanupHiddenCharacters = (s) => {
    const removeSymbols = new RegExp(/[\u200B]+/g);
    return s.replace(removeSymbols, "");
};
exports.cleanupHiddenCharacters = cleanupHiddenCharacters;