"use strict";
// Copyright 2022 Gnuxie <Gnuxie@protonmail.com>
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: Apache-2.0
//
// SPDX-FileAttributionText: <text>
// This modified file incorporates work from mjolnir
// https://github.com/matrix-org/mjolnir
// </text>
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProtectedRoomActivityTracker = void 0;
/**
 * Used to keep track of protected rooms so they are always ordered for activity.
 *
 * We use the same method as Element web for this, the major disadvantage being that we sort on each access to the room list (sort by most recently active first).
 * We have tried to mitigate this by caching the sorted list until the activity in rooms changes again.
 * See https://github.com/matrix-org/matrix-react-sdk/blob/8a0398b632dff1a5f6cfd4bf95d78854aeadc60e/src/stores/room-list/algorithms/tag-sorting/RecentAlgorithm.ts
 *
 */
class ProtectedRoomActivityTracker {
    protectedRoomActivities = new Map();
    /**
     * A slot to cache the rooms for `protectedRoomsByActivity` ordered so the most recently active room is first.
     */
    activeRoomsCache = null;
    /**
     * Inform the tracker that a new room is being protected by Draupnir.
     * @param roomId The room Draupnir is now protecting.
     */
    addProtectedRoom(roomId) {
        this.protectedRoomActivities.set(roomId, /* epoch */ 0);
        this.activeRoomsCache = null;
    }
    /**
     * Inform the trakcer that a room is no longer being protected by Draupnir.
     * @param roomId The roomId that is no longer being protected by Draupnir.
     */
    removeProtectedRoom(roomId) {
        this.protectedRoomActivities.delete(roomId);
        this.activeRoomsCache = null;
    }
    /**
     * Inform the tracker of a new event in a room, so that the internal ranking of rooms can be updated
     * @param roomId The room the new event is in.
     * @param event The new event.
     *
     */
    handleEvent(roomID, event) {
        const last_origin_server_ts = this.protectedRoomActivities.get(roomID);
        if (last_origin_server_ts !== undefined &&
            Number.isInteger(event.origin_server_ts)) {
            if (event.origin_server_ts > last_origin_server_ts) {
                this.activeRoomsCache = null;
                this.protectedRoomActivities.set(roomID, event.origin_server_ts);
            }
        }
    }
    /**
     * @returns A list of protected rooms ids ordered by activity.
     */
    protectedRoomsByActivity() {
        if (!this.activeRoomsCache) {
            this.activeRoomsCache = [...this.protectedRoomActivities]
                .sort((a, b) => b[1] - a[1])
                .map((pair) => pair[0]);
        }
        return this.activeRoomsCache;
    }
}
exports.ProtectedRoomActivityTracker = ProtectedRoomActivityTracker;
//# sourceMappingURL=ProtectedRoomActivityTracker.js.map