import { action, computed, makeObservable, observable, } from 'mobx';
import { EventEmitter } from 'events';
export class OptimisticPatch {
    constructor(params) {
        this.createdAt = Date.now();
        this.isStale = false;
        this.events = new EventEmitter();
        this.onEventuallyUpdated = () => {
            const { events, queryCache, queryNames, patches } = this;
            this.isStale = true;
            if (!events.listeners('scheduleRemoval').length) {
                patches.remove(this);
                queryNames.forEach((queryName) => {
                    queryCache
                        .findAll({ queryKey: [queryName] })
                        .forEach((q) => q.invalidate());
                });
            }
            else {
                events.emit('scheduleRemoval', this);
            }
        };
        this.patch = (item) => params.patch?.(item, this);
        this.selector = (item) => params.selector(item, this);
        this.actionType = params.actionType;
        this.keepPosition = params.keepPosition;
        this.queryNames = params.queryNames;
        this.queryCache = params.queryCache;
        this.patches = params.patches;
        this.move = params.move;
        this.collectionSnapshot = params.collectionSnapshot;
        this.afterItemKey = params.afterItemKey;
        this.patchedItems = observable.map(params.patchedItems, {
            deep: false,
        });
        this.originalItems = observable.map(params.originalItems, {
            deep: false,
        });
        this.originalTotal = params.originalTotal;
        makeObservable(this, {
            patchedItemsEntries: computed,
            isStale: observable.ref,
            onEventuallyUpdated: action,
        });
    }
    get patchedItemsEntries() {
        return Array.from(this.patchedItems.entries());
    }
}
//# sourceMappingURL=CollectionOptimisticPatch.js.map