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

import java.util.Collection;
import java.util.function.Function;

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

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

import de.ivu.elect.business.benutzerverwaltung.entity.Benutzer;
import de.ivu.elect.business.konfiguration.boundary.KonfigurationDAO;
import de.ivu.elect.business.konfiguration.entity.ElectSystemMandantKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.konfiguration.entity.KonfigurationMeta;
import de.ivu.elect.business.konfiguration.entity.KonfigurationTK;
import de.ivu.elect.business.mandant.boundary.MandantDAO;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.wahl.entity.Wahl;
import de.ivu.elect.business.wahl.entity.Wahltermin;
import de.ivu.elect.jee.entity.Meta;

@Stateless
public class KonfigurationCreator extends AbstractCustomParameterCreator<ElectSystemMandantKonfigurationWerte, Konfiguration, KonfigurationTK> {

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

  @Inject
  private transient KonfigurationDAO konfigurationDao;

  @Inject
  private transient KonfigurationMeta konfigurationMeta;

  @Inject
  private transient Instance<KonfigurationInit> konfigurationInits;

  @Inject
  private transient MandantDAO mandantDAO;

  public KonfigurationCreator() {
    super();
  }

  public void initKonfigurationAlleMandanten() {
    for (Mandant mandant : mandantDAO.findByAll()) {
      initKonfiguration(mandant);
    }
  }

  public void initKonfiguration(Mandant mandant) {
    LOG.info("Initialisiere für Mandant: " + mandant.getNummer());
    createOrUpdateDefaultParameters(null, null, mandant, null, konfigurationDao.findByMandant(mandant), konfigurationInits);
    LOG.info("Initialisiere für Mandant: " + mandant.getNummer() + " - done");
  }

  @Override
  protected void processParametersCreated(Collection<Konfiguration> parameters) {
    // Do nothing...
  }

  @Override
  protected Meta getEntityMeta() {
    return konfigurationMeta;
  }

  @Override
  protected Function<Konfiguration, KonfigurationTK> getEntityToTkFunktion() {
    return Konfiguration::getKonfigurationTK;
  }

  @Override
  protected void persistParameter(Wahltermin wahltermin, Wahl wahl, Mandant mandant, Benutzer benutzer, Konfiguration konfiguration) {
    konfiguration.setMandant(mandant);
    konfigurationDao.persist(konfiguration);
  }

  @Override
  protected void deleteParameter(Konfiguration konfiguration) {
    konfigurationDao.remove(konfiguration);
  }

  @Override
  protected Logger getLog() {
    return LOG;
  }
}
