
package de.ivu.elect.jee.presentation.dynamicform;

import static org.apache.commons.lang3.StringUtils.isBlank;

import java.util.ArrayList;
import java.util.List;

import javax.faces.convert.Converter;

import de.ivu.elect.jee.entity.Entity;
import de.ivu.elect.jee.faces.EntityConverter;

/**
 * @deprecated Use de.ivu.elect.jee.presentation.dynamicform.AbstractSelectOneAutoCompleteProperty<T> and de.ivu.elect.jee.presentation.dynamicform.AbstractSelectManyAutoCompleteProperty<T>
 */
@Deprecated
public abstract class AbstractAutocompletionProperty<E extends Entity< ? , ? >> extends AbstractProperty {

  private final List<E> entities;

  public AbstractAutocompletionProperty(List<E> entities) {
    super();

    this.entities = entities;
  }

  // ELECTMUC-2349
  public boolean isForceSelection() {
    return true; // LEGACY!
  }

  @Override
  protected boolean mustBeAccessableOnPageLoadByValue() {
    if (super.mustBeAccessableOnPageLoadByValue()) {
      return true;
    }

    return notAllEqual(getDefaultValue(), getValue());
  }

  @Override
  public Converter getDefaultConverter() {
    return EntityConverter.getInstance();
  }

  public List<E> getAllEntities() {
    return entities;
  }

  @Override
  public boolean getDefaultRequired() {
    return false;
  }

  public String getWatermark() {
    if (getAllEntities() == null || getAllEntities().isEmpty()) {
      return getMessage(AbstractAutoCompleteProperty.PLACEHOLDER_MSG_KEY_PREFIX + "empty");
    }

    return getMessage("component.autocomplete.watermark");
  }

  @Override
  public PropertyType getDefaultType() {
    return PropertyType.AUTO_COMPLETE_ENTITY;
  }

  public List<E> onComplete(String value) {
    List<E> result = new ArrayList<>();

    if (isBlank(value)) {
      result.addAll(entities);
    } else {
      String[] values = value.split(" "); // Alle Teile der Eingabe müssen passen, somit müssen Teile nicht in der korrekten Reihenfolge eingegeben werden, führen aber dennoch zum Ziel

      for (E entity : entities) {
        if (isMatchingAll(entity, values)) {
          result.add(entity);
        }
      }
    }

    return result;
  }

  protected boolean isMatchingAll(E entity, String[] values) {
    for (String value : values) {
      if (!isMatching(entity, value)) {
        return false;
      }
    }

    return true;
  }

  protected abstract boolean isMatching(E entity, String value);

  @Override
  protected boolean hasDefaultValue() {
    return notNullOrBlank(getDefaultValue());
  }

  public E getDefaultValue() {
    return null;
  }

  @Override
  public boolean hasValue() {
    return notNullOrBlank(getValue());
  }

  public abstract E getValue();

  public abstract void setValue(E entity);

  public abstract String getItemLabel(E entity);

  public void select() {
    // Do nothing...
  }

  public boolean isUseItemtip() {
    return false;
  }

  public String itemtipValue(E entity) {
    // Do nothing...
    return "";
  }
}
