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

import java.util.List;
import java.util.function.Function;

import javax.faces.convert.Converter;

import de.ivu.elect.business.wahl.boundary.AbstractWahlDAO;
import de.ivu.elect.business.wahl.entity.Wahl;
import de.ivu.elect.business.wahl.entity.WahlConstants;
import de.ivu.elect.jee.faces.EntityConverter;
import de.ivu.elect.jee.presentation.dynamicform.AbstractSelectOneMenuProperty;


import static java.util.Objects.nonNull;

/**
 *  on 09.08.2016.
 */
public abstract class AbstractWahlSelectOneMenuProperty extends AbstractSelectOneMenuProperty<Wahl> {

  private final List<Wahl> wahlen;

  private final Function<Wahl, String> labeler;

  private final boolean defaultRequired;

  private final boolean hasNoSelectionLabel;

  private final AbstractWahlDAO abstractWahlDAO;

  protected AbstractWahlSelectOneMenuProperty(AbstractWahlDAO abstractWahlDAO, List<Wahl> wahlen, Function<Wahl, String> labeler) {
    this(abstractWahlDAO, wahlen, labeler, false, true);
  }

  protected AbstractWahlSelectOneMenuProperty(AbstractWahlDAO abstractWahlDAO, List<Wahl> wahlen, Function<Wahl, String> labeler, boolean defaultRequired, boolean hasNoSelectionLabel) {
    this.abstractWahlDAO = abstractWahlDAO;
    this.wahlen = wahlen;
    this.labeler = labeler;
    this.defaultRequired = defaultRequired;
    this.hasNoSelectionLabel = hasNoSelectionLabel;
  }

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

  @Override
  public List<Wahl> getValues() {
    return wahlen;
  }

  @Override
  public String getItemLabel(Wahl wahl) {
    if (nonNull(wahl)) {
      return labeler.apply(abstractWahlDAO.attach(wahl));
    }

    return "";
  }

  @Override
  public String getDefaultLabel() {
    return getMessage(WahlConstants.MESSAGE_KEY_ENTITY_EINZAHL);
  }

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

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