import { MultipleChoiceField } from '@dvn/core/doldurma/src/fields/multiple-choice';
import { SingleChoiceField } from '@dvn/core/doldurma/src/fields/single-choice';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { getDataModelFieldDisplayValue } from '@dvn/core/models/data-model';
import { findField } from '@dvn/core/util/field';
export function filterList(listConfig, fields, list, textFilter) {
  if (!list || !textFilter) {
    return list;
  }
  return list.filter(item => {
    return (listConfig.body.fields || []).some(bodyFieldConfig => {
      const { fieldId } = bodyFieldConfig;
      const field = findField(fields, fieldId);
      if (!field) {
        console.error(`Field with id ${fieldId} not found. Available fields are ${fields.map(f => f.id).join(', ')}`);
      }
      const value = getDataModelFieldDisplayValue(item, field);
      if (field.type === TextField.type && containsText(value, textFilter)) {
        return true;
      }
      else if (field.type === MultipleChoiceField.type) {
        const matchesAnyOption = (value || []).some(optionValue => (containsText(field.getOptionOfValue(optionValue).label, textFilter)));
        if (matchesAnyOption) {
          return true;
        }
      }
      else if (field.type === SingleChoiceField.type) {
        const matchesAnyOption = containsText(field.getOptionOfValue(value).label, textFilter);
        if (matchesAnyOption) {
          return true;
        }
      }
      return false;
    });
  });
}
function containsText(value, filter) {
  return new RegExp(filter, 'i').test(value);
}
