export function nullOrEmpty(s) {
    return s == null || typeof s !== 'string' || s.length === 0;
}

export function contains(s, key, ignoreCase) {
    if (nullOrEmpty(s) || key == null) {
        return false;
    }
    if (typeof key !== 'string') {
        key = String(key);
    }
    if (ignoreCase) {
        return s.toLowerCase().includes(key.toLowerCase());
    }
    return s.includes(key);
}

export function endsWith(s, suffix) {
    if (nullOrEmpty(s) || nullOrEmpty(suffix)) {
        return false;
    }
    return s.endsWith(suffix); // === s.length - suffix.length;
}

export function padStart(s, num, char) {
    if (nullOrEmpty(s) || isNaN(num) || num <= s.length) {
        return s;
    }
    return (char ?? ' ').repeat(num - s.length);
}

export function formatUrl(msg) {
    //const urlReg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ig;
    //const urlArrray = str.match(urlReg);
    const p = /(http|ftp|https):\/\/.+?(\s|\r\n|\r|\n|\"|\'|\*|$)/g;
    const r = msg.match(p);
    msg = escapeHtml(msg);

    if (r?.length > 0) {
        const rs = [];
        for (let t of r) {
            t = t.replace(/["'\r\n ]/g, '');
            if (rs.indexOf(t) < 0) {
                rs.push(t);
            }
        }

        let path;
        if (typeof consts !== 'undefined') {
            path = consts.path;
        } else if (typeof _network !== 'undefined') {
            path = _network.root;
        } else if (typeof _net !== 'undefined') {
            path = _net.root;
        }
        for (let r of rs) {
            msg = msg.replaceAll(r, `<a target="_blank" href="${r}"><svg><use xlink:href="${path || ''}fonts/fa-regular.svg#link"></use></svg></a>`);
        }
    }

    return msg;
}

export function escapeHtml(text) {
    if (text == null) {
        return '';
    }
    return String(text)
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('\r\n', '<br/>')
        .replaceAll('\n', '<br/>')
        .replaceAll('  ', '&nbsp;');
}

export function escapeEmoji(text) {
    if (text == null) {
        return '';
    }
    if (typeof text !== 'string') {
        text = String(text);
    }
    return text
        .replace(/(=[A-Fa-f0-9]{2}){4}/g, s => decodeURIComponent(s.replaceAll('=', '%')))
        .replace(/&#x([0-9a-fA-F]{2,6});/g, (_, h) => String.fromCodePoint(parseInt(h, 16)));
}