import { useEntityList, useSortedEntities, useDesugaredRelativeSingleEntity } from "@contember/binding";
import { useMemo, 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 useDynamicMultipleChoiceWithConnectingEntityField = (props) => {
  const connectingEntitiesListAccessor = useEntityList(props);
  const sortedConnectingEntities = useSortedEntities(connectingEntitiesListAccessor, props.sortableBy);
  const optionTargetField = useDesugaredRelativeSingleEntity(props.connectingEntityField);
  const [currentlyChosenOptions, optionIdToConnectingEntityMap] = useMemo(() => {
    const currentlyChosenOptions2 = [];
    const optionIdToConnectingEntityMap2 = /* @__PURE__ */ new Map();
    for (const connectingEntity of sortedConnectingEntities.entities) {
      const optionEntity = connectingEntity.getRelativeSingleEntity(optionTargetField);
      currentlyChosenOptions2.push(optionEntity);
      optionIdToConnectingEntityMap2.set(optionEntity.id, connectingEntity);
    }
    return [currentlyChosenOptions2, optionIdToConnectingEntityMap2];
  }, [optionTargetField, sortedConnectingEntities.entities]);
  const { options, onSearch, isLoading } = useSelectOptions(props, currentlyChosenOptions);
  const currentValues = useCurrentValues(props, currentlyChosenOptions);
  const getConnectingEntityValues = connectingEntitiesListAccessor.getAccessor;
  const clear = useCallback(() => {
    getConnectingEntityValues().batchUpdates((getListAccessor) => {
      for (const child of getListAccessor()) {
        child.deleteEntity();
      }
    });
  }, [getConnectingEntityValues]);
  const onAdd = useCallback((option) => {
    sortedConnectingEntities.appendNew((accessor) => {
      const entity = accessor();
      const hasOne = optionTargetField.hasOneRelationPath;
      const parentEntity = entity.getRelativeSingleEntity({ hasOneRelationPath: hasOne.slice(0, -1) });
      parentEntity.connectEntityAtField(hasOne[hasOne.length - 1].field, option);
    });
  }, [optionTargetField.hasOneRelationPath, sortedConnectingEntities]);
  const errors = useAccessorErrors(connectingEntitiesListAccessor);
  return {
    currentValues,
    data: options,
    errors,
    onClear: clear,
    onAdd: useCallback((value) => {
      onAdd(value.value);
    }, [onAdd]),
    onRemove: useCallback((value) => {
      optionIdToConnectingEntityMap.get(value.value.id)?.deleteEntity();
    }, [optionIdToConnectingEntityMap]),
    onAddNew: useOnAddNew({
      ...props,
      connect: onAdd
    }),
    onMove: sortedConnectingEntities.moveEntity,
    onSearch,
    isLoading
  };
};
export { useDynamicMultipleChoiceWithConnectingEntityField };
//# sourceMappingURL=useDynamicMultipleChoiceWithConnectingEntityField.js.map
