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

import java.util.Comparator;
import java.util.stream.Collectors;

import javax.inject.Inject;

import de.ivu.elect.business.konfiguration.boundary.KonfigurationSearchParameters;
import de.ivu.elect.business.mandant.boundary.MandantExtendedDAO;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.mandant.entity.MandantConstants;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.jee.presentation.dynamicform.FormBuilder;
import de.ivu.elect.presentation.LambdaEntitySelectOneMenuProperty;
import de.ivu.elect.presentation.ViewFormBuilder;

public class KonfigurationSearchFormBuilder extends ViewFormBuilder {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient CustomParameterSearchFormBuilder customParameterSearchFormBuilder;

  @Inject
  private transient MandantExtendedDAO mandantExtendedDAO;

  public KonfigurationSearchFormBuilder() {
    super();
  }

  public void addProperties(FormBuilder formBuilder, KonfigurationSearchParameters searchParameters) {
    customParameterSearchFormBuilder.addProperties(formBuilder, searchParameters);
    if (isParameterAndererMandantenAenderbar()) {
      var mandanten = mandantExtendedDAO.findByAll().stream().sorted(Comparator.comparing(Mandant::getNummer)).collect(Collectors.toList());
      formBuilder.addProperty(new LambdaEntitySelectOneMenuProperty<Mandant>(mandanten, searchParameters::setMandant, searchParameters::getMandant,
          m -> getMessage("konfiguration.mandant.edit.mandant.labeler", m.getNummer(), m.getName()),
          MandantConstants.MESSAGE_KEY_ENTITY_EINZAHL,
          true, false));
    }
  }

  public boolean isParameterAndererMandantenAenderbar() {
    if (getMandant() == null) {
      return false;
    }

    return !getMandant().getArt().isCustomerMandant() && hasUseCasePermission(UseCasePermission.KONFIGURATION_MANDANT_EDIT);
  }
}
