import { createElement, Fragment } from "react";
import { Component, QueryLanguage, wrapFilterInHasOnes, useEntity, HasOne } from "@contember/binding";
import { renderDynamicChoiceFieldStatic } from "../../../fields/ChoiceField/renderDynamicChoiceFieldStatic.js";
import { SelectCellFilter } from "./SelectCellFilter.js";
import { useDesugaredOptionPath } from "../../../fields/ChoiceField/hooks/useDesugaredOptionPath.js";
import { DataGridColumn } from "../base/DataGridColumn.js";
import { FieldFallbackView } from "../../../fieldViews/FieldFallbackView.js";
const HasOneSelectCell = Component((props) => {
  return /* @__PURE__ */ createElement(DataGridColumn, {
    ...props,
    enableOrdering: false,
    getNewFilter: (filter, { environment }) => {
      if (filter.id.length === 0 && filter.nullCondition === false) {
        return void 0;
      }
      const desugared = QueryLanguage.desugarRelativeSingleEntity(props, environment);
      const conditions = [];
      if (filter.id.length > 0) {
        conditions.push({ in: filter.id });
      }
      if (filter.nullCondition === true) {
        conditions.push({ isNull: true });
      }
      return wrapFilterInHasOnes(desugared.hasOneRelationPath, {
        id: { or: conditions }
      });
    },
    emptyFilter: {
      id: [],
      nullCondition: false
    },
    filterRenderer: (filterProps) => /* @__PURE__ */ createElement(SelectCellFilter, {
      optionProps: {
        lazy: { initialLimit: 0 },
        ...props
      },
      ...filterProps
    })
  }, /* @__PURE__ */ createElement(HasOneSelectCellContent, {
    lazy: { initialLimit: 0 },
    ...props
  }));
}, "HasOneSelectField");
const HasOneSelectCellContent = Component((props) => {
  const desugaredOptionPath = useDesugaredOptionPath(props, void 0);
  const entity = useEntity(props).getEntity({ field: desugaredOptionPath.hasOneRelationPath });
  if ("renderOption" in props) {
    return /* @__PURE__ */ createElement(Fragment, null, props.renderOption(entity));
  }
  if ("field" in desugaredOptionPath) {
    const val = entity.getField(desugaredOptionPath).value;
    if (val !== null) {
      return /* @__PURE__ */ createElement(Fragment, null, val);
    }
    return /* @__PURE__ */ createElement(FieldFallbackView, {
      fallback: props.fallback,
      fallbackStyle: props.fallbackStyle
    });
  }
  return /* @__PURE__ */ createElement(Fragment, null);
}, (props, environment) => {
  const { subTree, renderedOption } = renderDynamicChoiceFieldStatic(props, environment);
  const { subTree: currentValuesSubtree } = renderDynamicChoiceFieldStatic(props, environment, { id: { in: [] } });
  return /* @__PURE__ */ createElement(Fragment, null, subTree, currentValuesSubtree, /* @__PURE__ */ createElement(HasOne, {
    field: props.field,
    expectedMutation: "none"
  }, renderedOption));
});
export { HasOneSelectCell };
//# sourceMappingURL=HasOneSelectCell.js.map
