var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { EntryType } from '../../../../../../CozoDb/types/entities';
import { extractSenseChats } from '../../utils/sense';
export const syncMyChats = (db, myAddress) => __awaiter(void 0, void 0, void 0, function* () {
    const syncItems = yield db.findSyncStatus({
        ownerId: myAddress,
        entryType: EntryType.chat,
    });
    const syncItemsMap = new Map(syncItems === null || syncItems === void 0 ? void 0 : syncItems.map((i) => [i.id, i]));
    const myTransactions = yield db.getTransactions(myAddress, 'asc');
    const myChats = extractSenseChats(myAddress, myTransactions);
    myChats.forEach((chat) => {
        const syncItem = syncItemsMap.get(chat.userAddress);
        const { hash, timestamp } = chat.transactions.at(-1);
        const lastChatTimestamp = timestamp;
        if (!syncItem) {
            db.putSyncStatus({
                ownerId: myAddress,
                entryType: EntryType.chat,
                id: chat.userAddress,
                timestampUpdate: lastChatTimestamp,
                unreadCount: chat.transactions.length,
                timestampRead: 0,
                disabled: false,
                lastId: hash,
                meta: chat.last,
            });
        }
        else {
            const { id, timestampRead, timestampUpdate } = syncItem;
            const unreadCount = chat.transactions.filter((t) => t.timestamp > timestampRead).length;
            if (timestampUpdate < lastChatTimestamp) {
                db.updateSyncStatus({
                    ownerId: myAddress,
                    id,
                    timestampUpdate: lastChatTimestamp,
                    unreadCount,
                    meta: chat.last,
                });
            }
        }
    });
});
//# sourceMappingURL=chat.js.map