import { useEntityList } from "@contember/binding";
import { useCallback } from "react";
import { useSelectOptions } from "./useSelectOptions.js";
import { useOnAddNew } from "./useOnAddNew.js";
import { useCurrentValues } from "./useCurrentValues.js";
import { useAccessorErrors } from "../../../errors/useAccessorErrors.js";
const useDynamicMultipleChoiceField = (props) => {
  const currentValueListAccessor = useEntityList(props);
  const currentlyChosenEntities = Array.from(currentValueListAccessor);
  const { options, onSearch, isLoading } = useSelectOptions(props, currentlyChosenEntities);
  const currentValues = useCurrentValues(props, currentlyChosenEntities);
  const getCurrentValues = currentValueListAccessor.getAccessor;
  const clear = useCallback(() => {
    getCurrentValues().batchUpdates((getListAccessor) => {
      for (const child of getListAccessor()) {
        getListAccessor().disconnectEntity(child);
      }
    });
  }, [getCurrentValues]);
  const errors = useAccessorErrors(currentValueListAccessor);
  return {
    currentValues,
    data: options,
    errors,
    onClear: clear,
    onAdd: useCallback((value) => {
      getCurrentValues().connectEntity(value.value);
    }, [getCurrentValues]),
    onRemove: useCallback((value) => {
      getCurrentValues().disconnectEntity(value.value);
    }, [getCurrentValues]),
    onAddNew: useOnAddNew({
      ...props,
      connect: useCallback((entity) => {
        getCurrentValues().connectEntity(entity);
      }, [getCurrentValues])
    }),
    onSearch,
    isLoading
  };
};
export { useDynamicMultipleChoiceField };
//# sourceMappingURL=useDynamicMultipleChoiceField.js.map
