"use strict";

exports.__esModule = true;
exports.useOptionalCachedState = useOptionalCachedState;
var _react = require("react");
var _WixPatternsRouterProvider = require("../providers/WixPatternsRouterProvider");
var _getCollectionComponentUniqueId = require("../utils/getCollectionComponentUniqueId");
var _bexCore = require("@wix/bex-core");
var _useSyncCollectionOnEntityCreate = require("./useSyncCollectionOnEntityCreate");
var _useSyncCollectionOnEntityUpdate = require("./useSyncCollectionOnEntityUpdate");
var _react2 = require("@wix/bex-core/react");
const getCachedState = ({
  shouldResetCache,
  uniqueId,
  router,
  container
}) => {
  const resetCache = shouldResetCache == null ? void 0 : shouldResetCache({
    router,
    uniqueId
  });
  if (resetCache) {
    router == null || router.stateRefs.delete(uniqueId);
    container.queryCache = new _bexCore.QueryCache();
  }
  return router == null ? void 0 : router.stateRefs.get(uniqueId);
};
function useOptionalCachedState(createState, {
  getCollectionsToUpdate,
  shouldResetCache
} = {}) {
  const container = (0, _react2.useWixPatternsContainer)();
  const router = (0, _WixPatternsRouterProvider.useWixPatternsRouter)();
  const [maybeNewState] = (0, _react.useState)(() => createState());
  const uniqueId = (0, _getCollectionComponentUniqueId.getCollectionComponentUniqueId)(maybeNewState);
  const [cachedState] = (0, _react.useState)(getCachedState({
    router,
    uniqueId,
    shouldResetCache,
    container
  }));
  (0, _useSyncCollectionOnEntityCreate.useSyncCollectionOnEntityCreate)(cachedState, getCollectionsToUpdate);
  (0, _useSyncCollectionOnEntityUpdate.useSyncCollectionOnEntityUpdate)(cachedState, getCollectionsToUpdate);
  const [state] = (0, _react.useState)(() => {
    if (router) {
      router.isUsingCache = !!cachedState;
    }
    if (cachedState) {
      return cachedState;
    }
    router == null || router.saveState(maybeNewState);
    return maybeNewState;
  });
  return state;
}
//# sourceMappingURL=useOptionalCachedState.js.map