
package de.ivu.elect.exchange;

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

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public abstract class AbstractValueExchangeMapper<E> implements Serializable {

  private static final long serialVersionUID = 1L;

  protected abstract Map<E, List<String>> getValuePerAliases();

  protected AbstractValueExchangeMapper() {
    super();
  }

  public E map(String value) {
    if (value != null) {
      String valueNormalized = normalizeSpace(value);

      for (Entry<E, List<String>> mapping : getValuePerAliases().entrySet()) {
        for (String alias : mapping.getValue()) {
          if (valueNormalized.equalsIgnoreCase(alias)) {
            return mapping.getKey();
          }
        }
      }
    }

    return mapValueUnbekannt(value);
  }

  protected E mapValueUnbekannt(String value) {
    return getValueUnbekannt();
  }

  protected abstract E getValueUnbekannt();

  public String map(E value) {
    if (getValuePerAliases().containsKey(value)) {
      return getAlias(value);
    }

    return mapAliasUnbekannt(value);
  }

  private String getAlias(E value) {
    return getValuePerAliases().get(value).get(0);
  }

  protected String mapAliasUnbekannt(E value) {
    return getAliasUnbekannt();
  }

  protected abstract String getAliasUnbekannt();
}
