import { computed, makeObservable } from 'mobx';
import { CollectionState } from './CollectionState';
import { addEventListener } from '../util';
export class FetchTotalState {
    constructor(params) {
        this._collection = params.collection;
        const { errorMonitor, errorHandler, onlineState, history, translate, queryCache, lodash, queryName, itemKey, itemName, paginationMode, selectionConsistencyMode, filters, query: { search }, } = params.collection;
        this._totalsCollection = new CollectionState({
            errorMonitor,
            errorHandler,
            onlineState,
            history,
            hooks: params.collection.hooks,
            translate,
            queryCache,
            lodash,
            queryName: `${queryName}.total`,
            itemKey,
            itemName,
            limit: 1,
            fetchData: async (query) => {
                const total = await params.fetchTotal(query);
                return { items: [], total };
            },
            paginationMode: paginationMode.id,
            selectionConsistencyMode,
            filters,
            search,
        });
        makeObservable(this, {
            total: computed,
            status: computed,
        });
    }
    init() {
        const { _collection, _totalsCollection } = this;
        const disposers = [
            _totalsCollection.init(),
            _collection._optimisticActions?.initCollection(_totalsCollection),
            addEventListener(_collection.emitter, 'search', () => {
                _totalsCollection.clearResultAndMoveToStart();
            }),
            addEventListener(_collection.emitter, 'clearSearch', _totalsCollection.clearResultAndMoveToStart),
            addEventListener(_collection.emitter, 'refreshAllPages', _totalsCollection.refreshAllPages),
            addEventListener(_collection.emitter, 'refreshCurrentPage', _totalsCollection.refreshCurrentPage),
        ];
        return () => {
            disposers.forEach((disposer) => disposer?.());
        };
    }
    get total() {
        return this._totalsCollection.result.total;
    }
    get status() {
        // While refreshing the status remains as success
        return this._totalsCollection.lifecycleState === 'refresh'
            ? 'loading'
            : this._totalsCollection.result.status.status;
    }
}
//# sourceMappingURL=FetchTotalState.js.map