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

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

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

import de.ivu.elect.business.datei.entity.DateiImportBerichtCustomData;
import de.ivu.elect.business.exchange.control.ImportExchange;
import de.ivu.elect.business.konfiguration.control.KonfigurationImportExchange;
import de.ivu.elect.business.konfiguration.entity.ElectSystemMandantKonfigurationWerte;
import de.ivu.elect.business.konfiguration.entity.Konfiguration;
import de.ivu.elect.business.konfiguration.entity.KonfigurationExchangeContext;
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.jee.entity.Meta;

@Stateless
public class KonfigurationImporter
    extends
      AbstractCustomParameterImporter<ElectSystemMandantKonfigurationWerte, Konfiguration, KonfigurationTK, KonfigurationExchangeContext> {

  @Inject
  private transient KonfigurationDAO konfigurationDAO;

  @Inject
  private transient KonfigurationMeta konfigurationMeta;

  @Inject
  private transient KonfigurationImportExchange importExchange;

  @Inject
  private transient MandantDAO mandantDAO;

  public KonfigurationImporter() {
    super();
  }

  @Override
  protected ImportExchange<List<Konfiguration>, KonfigurationExchangeContext> getExchange() {
    return importExchange;
  }

  @Override
  public Meta getMetaForEntityInternal() {
    return konfigurationMeta;
  }

  @Override
  protected List<Konfiguration> getAllEntitiesInDB(KonfigurationExchangeContext konfigurationExchangeContext) {
    return konfigurationDAO.findByMandant(konfigurationExchangeContext.getMandant());
  }

  @Override
  protected Function<Konfiguration, KonfigurationTK> getEntityToEntityTKFunction() {
    return KonfigurationTK.getKonfigurationToTKFunction();
  }

  @Override
  protected void persistiere(Collection<Konfiguration> konfigurationen, KonfigurationExchangeContext context,
      DateiImportBerichtCustomData dateiImportBerichtCustomData, StringBuilder bericht) {
    Mandant mandant = mandantDAO.attach(context.getMandant());
    for (Konfiguration konfiguration : konfigurationen) {
      if (konfiguration.getTemplate().isPresent()) { // keine ungültigen Werte importieren
        konfiguration.setMandant(mandant);
        konfigurationDAO.persist(konfiguration);
      }
    }
  }

  @Override
  protected void loescheAusDatenbank(Collection<Konfiguration> konfigurationenInDb, KonfigurationExchangeContext context,
      DateiImportBerichtCustomData dateiImportBerichtCustomData, StringBuilder bericht) {
    for (Konfiguration konfiguration : konfigurationenInDb) {
      konfigurationDAO.remove(konfiguration);
    }
  }
}
