"use strict";

exports.__esModule = true;
exports.useSyncCollectionOnEntityUpdate = useSyncCollectionOnEntityUpdate;
var _react = require("react");
var _useSyncCollectionOnEntityReturn = require("./useSyncCollectionOnEntityReturn");
function useSyncCollectionOnEntityUpdate(cachedState, getCollectionsToUpdate) {
  const updateCollection = (0, _react.useCallback)((collection, updatedEntity) => {
    collection.changeItem(updatedEntity);
  }, []);
  const checkIfViewSynced = (0, _react.useCallback)(async (collection, entity) => {
    var _collection$getKeyedI;
    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$getKeyedI = collection.getKeyedItem(itemKey)) == null ? void 0 : _collection$getKeyedI.indexWithinPage;
    const updatedData = await collection.fetchData(itemQuery);
    const newIndex = updatedData.items.findIndex(item => itemKey === collection.itemKey(item));
    return newIndex === currentIndex;
  }, [cachedState]);
  (0, _useSyncCollectionOnEntityReturn.useSyncCollectionOnEntityReturn)({
    cachedState,
    updateCollection,
    checkIfViewSynced,
    getEntityFromRouterState: state => state._updatedEntity,
    getCollectionsToUpdate
  });
}
//# sourceMappingURL=useSyncCollectionOnEntityUpdate.js.map