package ervu_dashboard.component.filter;

import component.field.dataconvert.DataConverter;
import component.field.dataconvert.DataConverterProvider;
import model.FilterModel;

import ru.cg.webbpm.modules.database.bean.entity_graph.EntityColumn;
import ru.cg.webbpm.modules.database.bean.entity_graph.condition.Operator;
import ru.cg.webbpm.modules.database.bean.filter.EntityFilter;
import ru.cg.webbpm.modules.database.bean.filter.FilterOperation;
import ru.cg.webbpm.modules.standard_annotations.editor.ObjectRef;
import ru.cg.webbpm.modules.standard_annotations.validation.NotNull;
import ru.cg.webbpm.modules.webkit.annotations.Model;
import ru.cg.webbpm.modules.webkit.beans.Behavior;

/**
 * @author Vitaly Chekushkin
 */
public abstract class AbstractFilterReference implements FilterReference {
  @NotNull
  @ObjectRef
  public Behavior filterComponent;

  public DataConverter<?, ?> dataConverter;

  public Operator multiValueOperator;

  @Override
  public String getSupportsFilterGuid() {
    return filterComponent.getObjectId();
  }

  @Override
  public EntityFilter toEntityFilter(FilterModel filterModel) {
    Object convertedValue = convertData(filterModel.getValue());
    FilterOperation operation = filterModel.getOperation();
    EntityColumn entityColumn = getEntityColumn();
    Operator multiValueOperator =
        this.multiValueOperator != null ? this.multiValueOperator : Operator.AND;

    return new EntityFilter(
        convertedValue,
        operation,
        entityColumn,
        multiValueOperator
    );
  }

  protected Object convertData(Object value) {
    DataConverter<Object, Object> converter =
        dataConverter != null
        ? (DataConverter<Object, Object>) dataConverter
        : (DataConverter<Object, Object>) DataConverterProvider.getDataConverter(value);
    return converter.convertValueForSave(value);
  }

  protected abstract EntityColumn getEntityColumn();
}
