"use strict";

exports.__esModule = true;
exports.useNestedTable = useNestedTable;
var _react = require("@wix/bex-core/react");
var _state = require("../state");
var _useOptionalCachedState = require("./useOptionalCachedState");
function useNestedTable(params) {
  const container = (0, _react.useWixPatternsContainer)();
  const getNestedCollection = (nestedTableState, entity) => {
    // if the entity has parent (in the code we check hardcoded parentId, we need to support other props)
    if (typeof entity.parentId === 'string') {
      const parentKeyedItem = nestedTableState.nested.getKeyedItem(entity.parentId);
      if (!parentKeyedItem) {
        return null;
      }
      const parentNodeState = parentKeyedItem.item.state.parentKeyToChildrenMap.get(entity.parentId);
      if (!parentNodeState) {
        return null;
      }
      return parentNodeState.collection;
    } else {
      var _nestedTableState$nes;
      return (_nestedTableState$nes = nestedTableState.nested.getKeyedItem(entity.id)) == null ? void 0 : _nestedTableState$nes.item.state.collection;
    }
  };
  const getCollectionsToUpdate = (cachedState, entity) => {
    var _nestedTableState$fla;
    const nestedTableState = cachedState;
    const nestedModeCollection = getNestedCollection(nestedTableState, entity);
    const flatModeCollection = (_nestedTableState$fla = nestedTableState.flat.keyedItems.find(
    // We need to get the keyItem, for now we use hardcoded id prop
    item => item.key === entity.id)) == null ? void 0 : _nestedTableState$fla.item.state.collection;
    return [nestedModeCollection, flatModeCollection].filter(Boolean);
  };
  const shouldResetCache = ({
    router,
    uniqueId
  }) => {
    var _router$currentState, _nestedTableState$nes2;
    const entity = router == null || (_router$currentState = router.currentState) == null ? void 0 : _router$currentState._updatedEntity;
    if (!entity) {
      return false;
    }
    const nestedTableState = router == null ? void 0 : router.stateRefs.get(uniqueId);
    const newParentId = entity.parentId;
    const oldParentId = nestedTableState == null || (_nestedTableState$nes2 = nestedTableState.nested.getKeyedItem(entity.id)) == null || (_nestedTableState$nes2 = _nestedTableState$nes2.item.originalKeyedItem) == null ? void 0 : _nestedTableState$nes2.item.parentId;
    return newParentId !== oldParentId;
  };
  const state = (0, _useOptionalCachedState.useOptionalCachedState)(() => new _state.NestedTableState({
    ...params,
    container
  }), {
    getCollectionsToUpdate,
    shouldResetCache
  });
  return state;
}
//# sourceMappingURL=useNestedTable.js.map