
package de.ivu.elect.business.konfiguration.boundary;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.konfiguration.entity.KonfigurationWertGeaendertEvent;
import de.ivu.elect.business.mandant.entity.MandantPK;


import static de.ivu.elect.business.konfiguration.entity.ElectSystemMandantKonfigurationWerte.bestimmeKeyEnum;

@javax.ejb.Stateless
public class KonfigurationEdit extends AbstractKonfigurationEdit {

  @Inject
  private transient KonfigurationWertGeaendertEvent konfigurationWertGeaendertEvent;

  @Override
  public void save(Konfiguration entity) {
    if (entity.hasChangedWert()) {
      sendKonfigurationChangeEvent(entity);
    }
    super.save(entity);
  }

  public void save(List<Konfiguration> entities) {
    saveSendChangeEvent(entities);
    flushToSave();
  }

  protected void saveSendChangeEvent(List<Konfiguration> entities) {
    for (var entity : entities) {
      sendKonfigurationChangeEvent(entity);
      validate(entity);
    }
  }

  public void sendKonfigurationChangeEvent(Konfiguration entity) {
    var keyValue = entity.getKey();
    var keyEnum = bestimmeKeyEnum(keyValue);
    konfigurationWertGeaendertEvent.sendWertGeaendertEvent(entity.getMandant(), keyEnum, entity.getWert(), keyValue);
  }

  public void saveFuerMandanten(Konfiguration entity, List<MandantPK> mandantPKs) {
    if (entity.getTemplate().isPresent()) {
      var electSystemMandantKonfigurationWerte = entity.getTemplate().get();
      List<Konfiguration> konfigurationen = new ArrayList<>();
      for (var konfiguration : dao.findByAll()) {
        if (mandantPKs.contains(konfiguration.getMandant().getPk())) {
          if (konfiguration.getTemplate().isPresent() && electSystemMandantKonfigurationWerte.equals(konfiguration.getTemplate().get())) {
            konfiguration.setWert(entity.getWert());
            konfigurationen.add(entity);
          }
        }
      }
      saveSendChangeEvent(konfigurationen);
    }
  }
}
