import { SingleChoiceField } from '@dvn/core/doldurma/src/fields/single-choice';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { Comparison } from '@dvn/core/models/filter';
export const getDefaultFilterValues = (config, fields) => {
  const filterValues = {};
  config.fields.forEach(fieldConfig => {
    const field = fieldConfig.field || fields.find(f => f.id === fieldConfig.fieldId);
    if (field.value) {
      filterValues[field.id] = field.value;
    }
  });
  return filterValues;
};
export const getFilterFields = (config, fields) => (config.fields.map(fieldConfig => fieldConfig.field || fields.find(f => f.id === fieldConfig.fieldId)));
export const generateDefaultFilters = (config, fields) => {
  const filterFields = getFilterFields(config, fields);
  return generateFilters(filterFields, getDefaultFilterValues(config, filterFields));
};
export const generateFilters = (filterFields, filterValues) => {
  const hasValidTextFilter = containsTextField(filterFields) && filterValues.text && filterValues.text !== '';
  const hasValidFilterThanText = containsSingleChoiceField(filterFields) && Object.keys(filterValues).length > 0;
  if (!hasValidTextFilter && !hasValidFilterThanText) {
    // if the text filter is not valid and there is no other filter
    return undefined;
  }
  if (hasValidTextFilter && !hasValidFilterThanText) {
    // return only text filter if there is no other filter
    return generateTextFilter(filterFields, filterValues);
  }
  if (!hasValidTextFilter && hasValidFilterThanText) {
    // return only single choice filter if there is no other filter
    return generateSingleChoiceFilter(filterFields, filterValues);
  }
  return {
    operator: 'and',
    filters: [
      generateTextFilter(filterFields, filterValues),
      generateSingleChoiceFilter(filterFields, filterValues),
    ]
  };
};
export const generateTextFilter = (filterFields, filterValues) => ({
  operator: 'or',
  filters: filterFields.map(field => ({
    comparison: Comparison.Contain,
    id: field.id,
    value: filterValues.text,
  }))
});
export const generateSingleChoiceFilter = (filterFields, filterValues) => ({
  operator: 'and',
  filters: filterFields
    .filter(field => field.type === SingleChoiceField.type)
    .filter(field => !!filterValues[field.id])
    .map(field => ({
    comparison: Comparison.Eq,
    id: field.id,
    value: filterValues[field.id],
  }))
});
export const containsTextField = (filterFields) => filterFields.some(field => field.type === TextField.type);
export const containsSingleChoiceField = (filterFields) => filterFields.some(field => field.type === SingleChoiceField.type);
