package de.ivu.elect.presentation.mandant;

import java.util.Set;
import java.util.stream.Collectors;

import javax.inject.Inject;
import javax.inject.Named;

import de.ivu.elect.business.mandant.boundary.MandantExtendedDAO;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.mandant.entity.MandantArt;
import de.ivu.elect.business.mandant.entity.MandantStatus;
import de.ivu.elect.jee.presentation.dynamicform.FormBuilder;
import de.ivu.elect.presentation.hilfe.OnlineHilfeId;
import de.ivu.elect.presentation.mandant.form.MandantViewFormBuilder;

@Named(AbstractMandantCreateView.COMPONENT_NAME)
@OnlineHilfeId("815")
public class MandantCreateView extends AbstractMandantCreateView {

  private static final long serialVersionUID = 1L;

  @Inject
  private MandantViewFormBuilder viewFormBuilder;

  @Inject
  private transient MandantExtendedDAO mandantExtendedDAO;

  public MandantCreateView() {
    super();
  }

  @Override
  protected void setEntity(Mandant entity) {
    super.setEntity(entity);
    if (!entity.isPersistent()) {
      entity.setArt(MandantArt.CUSTOMER);
      entity.setStatus(MandantStatus.AKTIVIERT);
      entity.setNummer(bestimmeNaechsteNummer());
    }
  }

  private Long bestimmeNaechsteNummer() {
    Set<Long> vergebeneNummern = mandantExtendedDAO.findByAll().stream().map(Mandant::getNummer).collect(Collectors.toSet());

    long result = 1;
    while (vergebeneNummern.contains(result)) {
      result++;
    }

    return result;
  }

  @Override
  public void addProperties(FormBuilder formBuilder, Mandant mandant) {
    viewFormBuilder.addProperties(formBuilder, mandant);
  }
}
