import { useCallback, useMemo } from 'react';
import { isMultiValueOperator } from '../AdHocFiltersVariable.js';
import { parseFilterExpression } from './utils.js';

function useFreeFormExpression({
  controller,
  filter,
  inputValue,
  filterInputType,
  allowCustomValue,
  isGroupBy,
  populateInputOnEdit
}) {
  const operatorValues = controller.getOperators().map((o) => o.value).filter((v) => Boolean(v));
  const expressionInputEnabled = allowCustomValue && !isGroupBy && filterInputType !== "value" && !populateInputOnEdit;
  const parseExpression = useCallback(
    (input) => {
      if (!input || !expressionInputEnabled) {
        return null;
      }
      const parsed = parseFilterExpression(input, operatorValues);
      if (!parsed) {
        return null;
      }
      if (filterInputType !== "operator" && !parsed.key) {
        return null;
      }
      return parsed;
    },
    [expressionInputEnabled, operatorValues, filterInputType]
  );
  const parsedExpression = useMemo(() => parseExpression(inputValue), [parseExpression, inputValue]);
  const canCommitExpressionUpdate = parsedExpression !== null;
  const canCommitFullExpression = Boolean(parsedExpression == null ? void 0 : parsedExpression.value);
  const commitExpressionUpdate = useCallback(() => {
    var _a;
    if (!parsedExpression || !filter) {
      return null;
    }
    const key = filterInputType === "operator" ? filter.key : parsedExpression.key;
    const keyLabel = filterInputType === "operator" ? (_a = filter.keyLabel) != null ? _a : filter.key : parsedExpression.key;
    if (!key) {
      return null;
    }
    const staged = { key, keyLabel, operator: parsedExpression.operator };
    if (!parsedExpression.value) {
      return staged;
    }
    if (isMultiValueOperator(parsedExpression.operator)) {
      const values = parsedExpression.value.split(",").map((v) => v.trim()).filter(Boolean);
      if (!values.length) {
        return staged;
      }
      return { ...staged, value: values[0], values, valueLabels: values };
    }
    return {
      ...staged,
      value: parsedExpression.value,
      valueLabels: [parsedExpression.value],
      values: void 0
    };
  }, [filter, filterInputType, parsedExpression]);
  return {
    parseExpression,
    canCommitExpressionUpdate,
    canCommitFullExpression,
    commitExpressionUpdate
  };
}

export { useFreeFormExpression };
//# sourceMappingURL=useFreeFormExpression.js.map
