"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const encode_url_1 = __importDefault(require("./encode_url"));
const escape_html_1 = __importDefault(require("./escape_html"));
const regexUrl = /(cite|download|href|src|url)$/i;
const regexMeta = /^(og:|twitter:)(audio|image|url|video|player)(:secure_url)?$/i;
function encSrcset(str) {
    str.split(' ')
        .forEach(subStr => {
        if (subStr.match(/\S/)) {
            subStr = subStr.trim();
            str = str.replace(subStr, (0, encode_url_1.default)(subStr));
        }
    });
    return str;
}
function htmlTag(tag, attrs, text, escape = true) {
    if (!tag)
        throw new TypeError('tag is required!');
    let result = `<${(0, escape_html_1.default)(tag)}`;
    for (const i in attrs) {
        if (attrs[i] == null)
            result += '';
        else {
            if (i.match(regexUrl)
                || (tag === 'meta' && !String(attrs[i]).match(regexMeta) && String(Object.values(attrs)[0]).match(regexMeta))) {
                result += ` ${(0, escape_html_1.default)(i)}="${(0, encode_url_1.default)(String(attrs[i]))}"`;
            }
            else if (attrs[i] === true || i === attrs[i])
                result += ` ${(0, escape_html_1.default)(i)}`;
            else if (i.match(/srcset$/i))
                result += ` ${(0, escape_html_1.default)(i)}="${encSrcset(String(attrs[i]))}"`;
            else
                result += ` ${(0, escape_html_1.default)(i)}="${(0, escape_html_1.default)(String(attrs[i]))}"`;
        }
    }
    if (escape && text && tag !== 'style')
        text = (0, escape_html_1.default)(String(text));
    if (text && tag === 'style') {
        text = text.replace(/url\(['"](.*?)['"]\)/gi, (urlAttr, url) => {
            return `url("${(0, encode_url_1.default)(url)}")`;
        });
    }
    if (text == null)
        result += '>';
    else
        result += `>${text}</${(0, escape_html_1.default)(tag)}>`;
    return result;
}
module.exports = htmlTag;
//# sourceMappingURL=html_tag.js.map