import { useWixPatternsContainer } from '@wix/bex-core/react';
import { NestedTableState } from '../state';
import { useOptionalCachedState } from './useOptionalCachedState';
export function useNestedTable(params) {
    const container = 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 {
            return nestedTableState.nested.getKeyedItem(entity.id)?.item.state
                .collection;
        }
    };
    const getCollectionsToUpdate = (cachedState, entity) => {
        const nestedTableState = cachedState;
        const nestedModeCollection = getNestedCollection(nestedTableState, entity);
        const flatModeCollection = nestedTableState.flat.keyedItems.find(
        // We need to get the keyItem, for now we use hardcoded id prop
        (item) => item.key === entity.id)?.item.state.collection;
        return [nestedModeCollection, flatModeCollection].filter(Boolean);
    };
    const shouldResetCache = ({ router, uniqueId, }) => {
        const entity = router?.currentState?._updatedEntity;
        if (!entity) {
            return false;
        }
        const nestedTableState = router?.stateRefs.get(uniqueId);
        const newParentId = entity.parentId;
        const oldParentId = nestedTableState?.nested.getKeyedItem(entity.id)?.item
            .originalKeyedItem?.item.parentId;
        return newParentId !== oldParentId;
    };
    const state = useOptionalCachedState(() => new NestedTableState({
        ...params,
        container,
    }), {
        getCollectionsToUpdate,
        shouldResetCache,
    });
    return state;
}
//# sourceMappingURL=useNestedTable.js.map