package de.ivu.elect.presentation.dashboard.entries;

import de.ivu.elect.business.konfiguration.boundary.KonfigurationExtendedDAO;
import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.security.control.ElectCommonPrincipal;
import de.ivu.elect.jee.presentation.dynamicform.FormBuilder;
import de.ivu.elect.jee.presentation.dynamicform.ReadOnlyStringProperty;
import de.ivu.elect.jee.presentation.status.OutputSeverity;
import de.ivu.elect.presentation.konfiguration.menu.KonfigurationUngueltigSearchMenuItemEntry;
import de.ivu.elect.presentation.menu.AbstractMenuItemEntry;

import javax.faces.application.FacesMessage;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UngueltigeSystemparameterDashboardEntry extends AbstractDashboardEntry {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient KonfigurationUngueltigSearchMenuItemEntry konfigurationUngueltigSearchMenuItemEntry;

  @Inject
  private transient KonfigurationExtendedDAO konfigurationExtendedDAO;

  @Inject
  private transient ElectCommonPrincipal principal;

  @Override
  public String getLegend() {
    return getMessage("dashboard.ungueltige.konfiguration.legend");
  }

  @Override
  protected void addProperties(FormBuilder formBuilder) {
    formBuilder.addSeparator("dashboard.ungueltige.konfiguration.separator");

    for (Konfiguration konfiguration : konfigurationExtendedDAO.findByMandant(principal.getMandant())) {
      List<ValidatorException> validate = konfiguration.validate();
      if (!validate.isEmpty()) {
        String name = konfiguration.getName(getMessages());
        String fehlerMeldung = bestimmeFehlermeldung(validate);
        formBuilder.addProperty(new ReadOnlyStringProperty(name, fehlerMeldung));
      }
    }

  }

  private String bestimmeFehlermeldung(List<ValidatorException> validate) {
    for (ValidatorException validatorException : validate) {
      if (validatorException.getFacesMessage().getSeverity().getOrdinal() >= FacesMessage.SEVERITY_ERROR.getOrdinal()) {
        return validatorException.getFacesMessage().getSummary();
      }
    }
    return validate.get(0).getFacesMessage().getSummary();
  }

  @Override
  public List<AbstractMenuItemEntry> getMenuItemsFirst() {
    List<AbstractMenuItemEntry> result = new ArrayList<>();
    result.add(konfigurationUngueltigSearchMenuItemEntry);
    return result;
  }

  @Override
  public List<AbstractMenuItemEntry> getMenuItemsLast() {
    return Collections.emptyList();
  }


  @Override
  protected OutputSeverity getSeverity() {
    return OutputSeverity.ERROR;
  }
}
