import { useExtendTree, useEnvironment } from "@contember/binding";
import { useDesugaredOptionPath } from "./useDesugaredOptionPath.js";
import { useMemo, useState, useEffect } from "react";
import { useTopLevelOptionAccessors } from "./useTopLevelOptionAccessor.js";
import { renderDynamicChoiceFieldStatic } from "../renderDynamicChoiceFieldStatic.js";
const useCurrentlyChosenEntities = (optionProps, ids) => {
  const filter = useMemo(() => ({
    id: { in: ids }
  }), [ids]);
  const [renderedState, setRenderedState] = useState({
    treeRootId: void 0,
    filter: { id: { in: [] } }
  });
  const desugaredOptionPath = useDesugaredOptionPath(optionProps, renderedState.filter);
  const extendTree = useExtendTree();
  const environment = useEnvironment();
  useEffect(() => {
    if (renderedState.filter === filter || !optionProps.lazy) {
      return;
    }
    (async () => {
      const { subTree } = renderDynamicChoiceFieldStatic({
        ...optionProps,
        createNewForm: void 0
      }, environment, filter);
      const treeRootId = await extendTree(subTree);
      if (treeRootId) {
        setRenderedState({
          treeRootId,
          filter
        });
      }
    })();
  }, [environment, extendTree, filter, optionProps, renderedState.filter]);
  return useTopLevelOptionAccessors(desugaredOptionPath, renderedState.treeRootId);
};
export { useCurrentlyChosenEntities };
//# sourceMappingURL=useCurrentlyChosenEntities.js.map
