import { G as chatUnreadTimestamps } from './ui-store-76bb0e8e.js';

const parseMessageForTarget = (message) => {
    let parsedMessage = null;
    try {
        const parsed = JSON.parse(message.message);
        const { target, message: m } = parsed;
        if (target === undefined || m === undefined) {
            parsedMessage = message;
        }
        else {
            parsedMessage = Object.assign(Object.assign({}, message), { targetUserIds: target, message: m });
        }
    }
    catch (error) {
        parsedMessage = message;
    }
    return parsedMessage;
};
/**
 * Generate a unique chat group key used in `<rtk-chat /> and <rtk-chat-selector-ui />`
 * @param ids An array of user ids
 * @returns A unique key from the user ids
 */
function generateChatGroupKey(ids) {
    return ids.sort((a, b) => a.localeCompare(b)).join('_');
}
function handleFilesDataTransfer(items, callback) {
    if (items == null)
        return true;
    for (const item of items) {
        if (item.kind === 'file') {
            const file = item.getAsFile();
            if (item.type.startsWith('image/')) {
                callback('image', file);
            }
            else {
                callback('file', file);
            }
        }
    }
}
function getChatGroups({ messages, participants, selfUserId }) {
    const groups = {};
    // create empty chat groups for all participants
    for (const participant of participants) {
        groups[generateChatGroupKey([participant.userId, selfUserId])] = [];
    }
    messages.forEach((message) => {
        var _a;
        const parsedMessage = parseMessageForTarget(message);
        let key = 'everyone';
        if (((_a = parsedMessage.targetUserIds) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            const allParticipants = new Set([
                parsedMessage.userId,
                ...parsedMessage.targetUserIds,
            ]);
            key = generateChatGroupKey(Array.from(allParticipants));
        }
        if (!groups[key]) {
            groups[key] = [];
        }
        groups[key].push({ type: 'chat', message: parsedMessage });
    });
    return groups;
}
function getUnreadChatCounts({ messages, selfUserId, selectedGroupId, participants, }) {
    var _a;
    const groups = getChatGroups({
        messages,
        selfUserId,
        participants,
    });
    const unreadCounts = {};
    for (const key in groups) {
        const lastReadTimestamp = (_a = chatUnreadTimestamps[key]) !== null && _a !== void 0 ? _a : 0;
        if (key === selectedGroupId) {
            // reset count to 0 when you select a group
            unreadCounts[key] = 0;
            chatUnreadTimestamps[key] = new Date();
        }
        else {
            unreadCounts[key] = groups[key].filter((c) => {
                return (c.type == 'chat' && c.message.time > lastReadTimestamp && c.message.userId !== selfUserId);
            }).length;
        }
    }
    return unreadCounts;
}
function getParticipantUserId({ groupId, selfUserId, }) {
    return groupId.split('_').find((id) => id != selfUserId);
}
function reverse(str) {
    return str.split('').reverse().join('');
}
const boldPattern = /^\*([^*\s]+)\*/;
const italicsPattern = /^_([^_\s]+)_/;
const strikethroughPattern = /^~([^~\s]+)~/;
// Source: https://stackoverflow.com/a/8234912/2013580
const linkPattern = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.,~#?&//=]*)/;
const replyBlockPattern = /<blockquote>[.\s\S]*<\/blockquote>\n\n/m;
function extractReplyBlock(message, excludeTags = false) {
    if (!replyBlockPattern.test(message)) {
        return '';
    }
    let startOffset = 0;
    let endOffset = '</blockquote>'.length;
    if (excludeTags) {
        startOffset = '<blockquote>'.length;
        endOffset = 0;
    }
    return message.substring(message.indexOf('<blockquote>') + startOffset, message.indexOf('</blockquote>') + endOffset);
}
function stripOutReplyBlock(message) {
    return message.replace(replyBlockPattern, '');
}
const MAX_TEXT_LENGTH = 2000;
const KNOWN_TAGS = ['<a>', '<b>', '<i>', '<q>', '<s>'];
function parseRichText(text) {
    text = text
        .split(' ')
        .map((word) => {
        if (linkPattern.test(word)) {
            const res = linkPattern.exec(word);
            word = word.replace(res[0], `<a>${res[0]}</a>`);
        }
        else {
            if (boldPattern.test(word)) {
                const res = boldPattern.exec(word);
                word = word.replace(res[0], `<b>${res[1]}</b>`);
            }
            if (italicsPattern.test(word)) {
                const res = italicsPattern.exec(word);
                word = word.replace(res[0], `<i>${res[1]}</i>`);
            }
            if (strikethroughPattern.test(word)) {
                const res = strikethroughPattern.exec(word);
                word = word.replace(res[0], `<s>${res[1]}</s>`);
            }
        }
        return word;
    })
        .join(' ');
    text = text
        .split(' ')
        .map((word, idx) => {
        if (word === '>' && (idx === 0 || word[idx - 1] === '>')) {
            return `<q></q>`;
        }
        return word;
    })
        .join(' ');
    const [tokens] = tokenizeRichText(text);
    return tokens;
}
function tokenizeRichText(text, endTag = '') {
    const tokens = [];
    if (text.length === 0) {
        return [tokens, 0];
    }
    let i = 0;
    while (i < text.length) {
        if (endTag.length && endTag === text.substring(i, i + endTag.length)) {
            return [tokens, i + endTag.length];
        }
        if (KNOWN_TAGS.includes(text.substring(i, i + 3))) {
            const [subtokens, pos] = tokenizeRichText(text.substring(i + 3), `</${text[i + 1]}>`);
            tokens.push({
                type: text[i + 1],
                content: subtokens.length === 1 && subtokens[0].type === 'plain_text'
                    ? subtokens[0].content
                    : subtokens,
            });
            i += pos + 3;
        }
        else {
            let top = tokens[tokens.length - 1];
            if (!top || top.type !== 'plain_text') {
                tokens.push({ type: 'plain_text', content: '' });
                top = tokens[tokens.length - 1];
            }
            top.content += text[i];
            i++;
        }
    }
    return [tokens, i];
}

export { MAX_TEXT_LENGTH as M, getChatGroups as a, getUnreadChatCounts as b, getParticipantUserId as c, replyBlockPattern as d, extractReplyBlock as e, parseMessageForTarget as f, generateChatGroupKey as g, handleFilesDataTransfer as h, parseRichText as p, reverse as r, stripOutReplyBlock as s };
