class NotificationCache {
    constructor() {
        this.PAGE_SIZE = 10;
        this.cache = new Map();
        this.currentPage = 0;
    }
    observePageUpdate(callback) {
        this.onPageUpdate = callback;
    }
    setCurrentPage(page) {
        this.currentPage = page;
        this.syncCurrentPage();
    }
    updateCache(notifications) {
        this.resetCache();
        const pageCount = Math.ceil(notifications.length / this.PAGE_SIZE);
        for (let i = 0; i < pageCount; i++) {
            const pageNotifications = notifications.slice(i * this.PAGE_SIZE, (i + 1) * this.PAGE_SIZE);
            const hasMore = i < pageCount - 1;
            this.cache.set(i, { notifications: pageNotifications, hasMore });
        }
        this.syncCurrentPage();
    }
    syncCurrentPage() {
        var _a;
        const entry = this.cache.get(this.currentPage);
        const notifications = (_a = entry === null || entry === void 0 ? void 0 : entry.notifications) !== null && _a !== void 0 ? _a : [];
        const hasMore = entry === null || entry === void 0 ? void 0 : entry.hasMore;
        this.onPageUpdate([...notifications], hasMore);
    }
    deleteById(id) {
        const updatedNotifications = this.getAllFromCache().filter((n) => n.id !== id);
        this.updateCache(updatedNotifications);
    }
    addToFront(notification) {
        if (!this.cache.get(0)) {
            return;
        }
        const updatedNotifications = [notification, ...this.getAllFromCache()];
        this.updateCache(updatedNotifications);
    }
    markAsRead(id, mark) {
        const updatedNotifications = this.getAllFromCache().map((n) => (n.id === id ? Object.assign(Object.assign({}, n), mark) : n));
        this.updateCache(updatedNotifications);
    }
    markAllAsRead() {
        const updatedNotifications = this.getAllFromCache().map((n) => (Object.assign(Object.assign({}, n), { read: true, seen: true })));
        this.updateCache(updatedNotifications);
    }
    clearAll() {
        this.resetCache();
        this.setCurrentPage(0);
    }
    resetCache() {
        this.cache.clear();
        this.cache.set(0, { notifications: [], hasMore: false });
    }
    async loadPageFromApi(page, loader) {
        if (this.cache.has(page)) {
            this.setCurrentPage(page);
            return;
        }
        const data = await loader();
        this.cache.set(page, { notifications: data.notifications, hasMore: data.hasMore });
        this.setCurrentPage(page);
    }
    getAllFromCache() {
        return Array.from(this.cache.values()).flatMap((entry) => entry.notifications);
    }
}
export const notificationCache = new NotificationCache();
