import { useCallback } from 'react';
import { useSyncCollectionOnEntityReturn } from './useSyncCollectionOnEntityReturn';
export function useSyncCollectionOnEntityUpdate(cachedState, getCollectionsToUpdate) {
    const updateCollection = useCallback((collection, updatedEntity) => {
        collection.changeItem(updatedEntity);
    }, []);
    const checkIfViewSynced = useCallback(async (collection, entity) => {
        const itemKey = collection.itemKey(entity);
        let fetchedPageInfo = null;
        for (let fetchIndex = collection.fetchesHistory.length - 1; fetchIndex >= 0; fetchIndex--) {
            const fetch = collection.fetchesHistory[fetchIndex];
            if (fetch.itemsKeys.some((fetchedItemKey) => fetchedItemKey === itemKey)) {
                fetchedPageInfo = fetch.queryPageInfo;
                break;
            }
        }
        if (!fetchedPageInfo) {
            console.error('Fetched page info for updated entity not found');
            return false;
        }
        const itemQuery = {
            ...collection.query.asComputed,
            ...fetchedPageInfo,
        };
        const currentIndex = collection.getKeyedItem(itemKey)?.indexWithinPage;
        const updatedData = await collection.fetchData(itemQuery);
        const newIndex = updatedData.items.findIndex((item) => itemKey === collection.itemKey(item));
        return newIndex === currentIndex;
    }, [cachedState]);
    useSyncCollectionOnEntityReturn({
        cachedState,
        updateCollection,
        checkIfViewSynced,
        getEntityFromRouterState: (state) => state._updatedEntity,
        getCollectionsToUpdate,
    });
}
//# sourceMappingURL=useSyncCollectionOnEntityUpdate.js.map