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

import java.util.function.Function;

import javax.faces.convert.Converter;
import javax.faces.convert.EnumConverter;

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

public abstract class AbstractEnumProperty<E extends Enum<E>> extends AbstractSelectOneMenuProperty<E> {

  protected Function<E, String> itemLabeler = null;

  protected AbstractEnumProperty() {
    super();
  }

  @Override
  public Converter getDefaultConverter() {
    return new EnumConverter(getEnumClass());
  }

  @Override
  public String getItemLabel(E value) {
    if (itemLabeler == null) {
      return getMessage(getItemLabelMessageKey(value));
    }

    return itemLabeler.apply(value);
  }

  protected String getItemLabelMessageKey(E value) {
    if (value == null) {
      return "";
    }

    return FacesMessageUtil.getEnumMessageKey(value);
  }

  protected abstract Class<E> getEnumClass();

  public Class<E> getPropertyEnumClass() {
    return getEnumClass();
  }

  @Override
  public String getNoSelectionLabel() {
    if (noSelectionLabel != null) {
      return noSelectionLabel;
    }

    return getMessage(FacesMessageUtil.getEnumMessageKeyPrefix(getEnumClass()));
  }

  public void setItemLabeler(Function<E, String> itemLabeler) {
    this.itemLabeler = itemLabeler;
  }
}
