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

import javax.annotation.Nullable;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;

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

import de.ivu.elect.business.mandant.boundary.MandantDAO;
import de.ivu.elect.business.mandant.boundary.MandantEdit;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.mandant.entity.MandantPK;

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class MandantResetTransaction {

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

  @Inject
  private transient MandantDAO mandantDAO;

  @Inject
  private transient MandantEdit mandantEdit;

  @Inject
  private transient MandantCreate mandantCreate;

  @Nullable
  public Mandant remove(MandantPK mandantPK) {
    Mandant alt = mandantDAO.findByPrimaryKey(mandantPK);
    if (alt == null || !alt.getArt().isResetMoeglich() /*lieber einmal zu viel prüfen*/) {
      return null;
    }
    LOG.info("Mandant reset: " + alt);
    Mandant neu = new Mandant();
    alt.copyEntityAttributesUsingSetter(neu);
    mandantEdit.delete(alt);
    return neu;
  }

  public void create(Mandant neuerMandant) {
    mandantCreate.save(neuerMandant);
  }
}
