
package de.ivu.elect.presentation.gebietsbaum.form;

import java.util.List;

import javax.faces.convert.Converter;

import de.ivu.elect.business.benutzerverwaltung.entity.Rolle;
import de.ivu.elect.jee.faces.EntityAusPerTkListeConverter;
import de.ivu.elect.jee.faces.EntityConverter;
import de.ivu.elect.jee.presentation.dynamicform.AbstractSelectOneMenuProperty;
import de.ivu.elect.jee.presentation.dynamicform.PropertyType;

public abstract class AbstractEntityRolleProperty<E> extends AbstractSelectOneMenuProperty<Rolle> {

  private final E entity;

  private final List<Rolle> values;

  private final String noSelectionLabel;

  public AbstractEntityRolleProperty(E entity, List<Rolle> values, String noSelectionLabel) {
    super();

    this.entity = entity;
    this.values = values;
    this.noSelectionLabel = noSelectionLabel;
  }

  @Override
  public Converter getDefaultConverter() {
    if (isNichtPersistenteRolleVorhanden(values)) {
      return new EntityAusPerTkListeConverter<>(values);
    }

    return EntityConverter.getInstance();
  }

  @Override
  public String getNoSelectionLabel() {
    return noSelectionLabel;
  }

  @Override
  public abstract boolean getDefaultRequired();

  @Override
  public boolean hasNoSelectionItem() {
    return true;
  }

  @Override
  public abstract String getDefaultLabel();

  @Override
  public List<Rolle> getValues() {
    return values;
  }

  @Override
  public String getItemLabel(Rolle item) {
    if (item == null) {
      return getNoSelectionLabel();
    }

    return item.getName();
  }

  private boolean isNichtPersistenteRolleVorhanden(List<Rolle> values) {
    for (Rolle value : values) {
      if (!value.isPersistent()) {
        return true;
      }
    }
    return false;
  }

  public E getEntity() {
    return entity;
  }

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