import { useMemo, useCallback } from "react";
import { useEnvironment, QueryLanguage, useEntity, useAccessorUpdateSubscription } from "@contember/binding";
import { useSelectOptions } from "./useSelectOptions.js";
import { useOnAddNew } from "./useOnAddNew.js";
import { useCurrentValues } from "./useCurrentValues.js";
import { useAccessorErrors } from "../../../errors/useAccessorErrors.js";
const useDynamicSingleChoiceField = (props) => {
  const [currentValueEntity, currentValueParent, currentValueFieldName] = useCurrentAccessors(props);
  const currentlyChosenEntities = useMemo(() => currentValueEntity.existsOnServer || currentValueEntity.hasUnpersistedChanges ? [currentValueEntity] : [], [currentValueEntity]);
  const { options, onSearch, isLoading } = useSelectOptions(props, currentlyChosenEntities);
  const currentValues = useCurrentValues(props, currentlyChosenEntities);
  const errors = useAccessorErrors(currentValueEntity);
  return {
    data: options,
    errors,
    currentValue: currentValues.length ? currentValues[0] : null,
    onSelect: (value) => {
      currentValueParent.connectEntityAtField(currentValueFieldName, value.value);
    },
    onClear: () => {
      currentValueParent.disconnectEntityAtField(currentValueFieldName);
    },
    onAddNew: useOnAddNew({
      ...props,
      connect: useCallback((entity) => {
        currentValueParent.connectEntityAtField(currentValueFieldName, entity);
      }, [currentValueFieldName, currentValueParent])
    }),
    onSearch,
    isLoading
  };
};
const useCurrentAccessors = (props) => {
  const environment = useEnvironment();
  const desugaredRelativePath = useMemo(() => {
    return QueryLanguage.desugarRelativeSingleEntity(props, environment);
  }, [environment, props]);
  const hasOneRelationPath = desugaredRelativePath.hasOneRelationPath;
  const parentEntity = useEntity();
  const lastHasOneRelation = hasOneRelationPath[hasOneRelationPath.length - 1];
  const currentValueFieldName = lastHasOneRelation.field;
  const getCurrentValueParent = useCallback(() => {
    return parentEntity.getRelativeSingleEntity({
      hasOneRelationPath: desugaredRelativePath.hasOneRelationPath.slice(0, -1)
    });
  }, [desugaredRelativePath.hasOneRelationPath, parentEntity]);
  const currentValueParent = useAccessorUpdateSubscription(getCurrentValueParent);
  const currentValueEntity = useMemo(() => {
    return currentValueParent.getRelativeSingleEntity({ hasOneRelationPath: [lastHasOneRelation] });
  }, [currentValueParent, lastHasOneRelation]);
  return [currentValueEntity, currentValueParent, currentValueFieldName];
};
export { useDynamicSingleChoiceField };
//# sourceMappingURL=useDynamicSingleChoiceField.js.map
