
package de.ivu.elect.business.system.control;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.business.benutzerverwaltung.control.RechteKonfigurationAktualisierenEvent;
import de.ivu.elect.business.konfiguration.entity.KonfigurationLoader;
import de.ivu.elect.business.mandant.boundary.MandantDAO;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.system.boundary.SystemStatusStore;
import de.ivu.elect.business.system.entity.SystemStatus;


import static de.ivu.elect.business.konfiguration.entity.MandantKonfigurationWerte.SYSTEM_STATUS;

@Stateless
public class SystemStatusInit {

  private static final Logger LOG = LoggerFactory.getLogger(SystemStatusInit.class);

  @Inject
  private transient KonfigurationLoader konfigurationLoader;

  @Inject
  private transient SystemStatusStore systemStatusStore;

  @Inject
  private transient MandantDAO mandantDAO;

  @Inject
  private transient RechteKonfigurationAktualisierenEvent rechteKonfigurationAktualisierenEvent;

  public SystemStatusInit() {
    super();
  }

  public void initAlleMandanten() {
    for (Mandant mandant : mandantDAO.findByAll()) {
      init(mandant);
    }
    rechteKonfigurationAktualisierenEvent.sendChangeEvent();
  }

  public void init(Mandant mandant) {
    SystemStatus systemStatus = ermittleSystemStatus(mandant);
    LOG.info("Mandant: " + mandant.getNummer() + " - Systemstatus ermittelt: " + systemStatus);
    systemStatusStore.setSystemStatus(mandant.getPk(), systemStatus);
  }

  private SystemStatus ermittleSystemStatus(Mandant mandant) {
    SystemStatus systemStatus = konfigurationLoader.resolveEnumValue(mandant, SYSTEM_STATUS, SystemStatus.class);

    LOG.info("Systemstatus laut DB: " + systemStatus);

    return systemStatus;
  }
}
