import { kinds } from "nostr-tools";
import { getLegacyMessageCorraspondant, getLegacyMessageParent } from "../helpers/legacy-messages.js";
import { map } from "rxjs";
import { getConversationIdentifierFromMessage, getConversationParticipants } from "../helpers/messages.js";
/** A model that returns all legacy message groups (1-1) that a pubkey is participating in */
export function LegacyMessagesGroups(self) {
    return (store) => store.timeline({ kinds: [kinds.EncryptedDirectMessage], "#p": [self] }).pipe(map((messages) => {
        const groups = {};
        for (const message of messages) {
            const id = getConversationIdentifierFromMessage(message);
            if (!groups[id] || groups[id].created_at < message.created_at)
                groups[id] = message;
        }
        return Object.values(groups).map((message) => ({
            id: getConversationIdentifierFromMessage(message),
            participants: getConversationParticipants(message),
            lastMessage: message,
        }));
    }));
}
/** Returns all legacy direct messages in a group */
export function LegacyMessagesGroup(self, corraspondant) {
    return (store) => store.timeline([
        {
            kinds: [kinds.EncryptedDirectMessage],
            "#p": [self],
            authors: [corraspondant],
        },
        {
            kinds: [kinds.EncryptedDirectMessage],
            "#p": [corraspondant],
            authors: [self],
        },
    ]);
}
/** Returns an array of legacy messages that have replies */
export function LegacyMessageThreads(self, corraspondant) {
    return (store) => store.model(LegacyMessagesGroup, self, corraspondant).pipe(map((messages) => messages.filter((message) => 
    // Only select messages that are not replies
    !getLegacyMessageParent(message) &&
        // Check if message has any replies
        store.getByFilters({ "#e": [message.id], kinds: [kinds.EncryptedDirectMessage] }).size > 0)));
}
/** Returns all the legacy direct messages that are replies to a given message */
export function LegacyMessageReplies(self, message) {
    const corraspondant = getLegacyMessageCorraspondant(message, self);
    return (store) => store.timeline([
        {
            kinds: [kinds.EncryptedDirectMessage],
            "#p": [self],
            authors: [corraspondant],
            "#e": [message.id],
        },
        {
            kinds: [kinds.EncryptedDirectMessage],
            "#p": [corraspondant],
            authors: [self],
            "#e": [message.id],
        },
    ]);
}
