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

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

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.annotation.Nullable;
import javax.faces.convert.Converter;

import de.ivu.elect.jee.faces.FacesMessageUtil;

public abstract class AbstractAutoCompleteOptionsProvider<T> implements Serializable {

  private static final long serialVersionUID = 1L;

  public AbstractAutoCompleteOptionsProvider() {
    super();
  }

  @Nullable
  public T tryGetOptionByQuery(String query) {
    List<T> optionsFiltered = streamOptionsFiltered(query).stream().limit(2).collect(Collectors.toList());

    if (optionsFiltered.size() == 1) {
      return optionsFiltered.get(0);
    }

    return null;
  }

  public List<T> streamOptionsFiltered(String query, boolean blankQueryCausesEmptyResult) {
    if (isBlank(query)) {
      if (blankQueryCausesEmptyResult) {
        return Collections.emptyList();
      }

      return streamOptions();
    }

    return streamOptionsFiltered(query);
  }

  protected List<T> streamOptionsFiltered(String query) {
    return streamOptions().stream().filter(matchesQuery(trim(query))).collect(Collectors.toList());
  }

  protected List<T> streamOptions() {
    return getOptions();
  }

  protected abstract List<T> getOptions();

  protected abstract Predicate< ? super T> matchesQuery(String query);

  public abstract Converter getConverter();

  protected String getMessage(Enum< ? > value) {
    return getMessage(FacesMessageUtil.getEnumMessageKey(value));
  }

  protected String getMessage(String msgKey, Object... params) {
    return FacesMessageUtil.getResourceText(msgKey, params);
  }
}
