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

import javax.inject.Inject;

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

import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.mandant.entity.MandantPK;

public abstract class AbstractElectMandantBackgroundService extends AbstractElectBackgroundService {

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

  @Inject
  private transient MandantBackgroundServiceHelper mandantBackgroundServiceHelper;

  public AbstractElectMandantBackgroundService() {
    super();
  }

  @Override
  protected boolean isSomethingToDoInternal() {
    for (MandantPK mandantPK : mandantBackgroundServiceHelper.getMandanten()) {
      try {
        if (isSomethingToDoInternal(mandantPK)) {
          return true;
        }
      } catch (Exception e) {
        logExceptionFuerMandant(mandantPK, e);
        throw e;
      }
    }
    return false;
  }

  private void logExceptionFuerMandant(MandantPK mandantPK, Exception exception) {
    try {
      if (!isRetryAfterException(exception)) {
        mandantBackgroundServiceHelper.systemLogExcpetionFuerKundenMandant(mandantPK, exception, getSystemLogQuelle());
      }
    } catch (Exception e) {
      // ignorieren
      LOG.error("Fehler beim Loggen der Exception: ", e);
      LOG.error("Fehler beim Loggen von Quelle: " + getSystemLogQuelle() + ", fuer Mandant: " + mandantPK + ", der folgenden Exception: " + exception.getMessage(), exception);
    }
  }

  protected abstract boolean isSomethingToDoInternal(MandantPK mandantPK);

  @Override
  protected void doSomethingInternal() {
    for (MandantPK mandantPK : mandantBackgroundServiceHelper.getMandanten()) {
      try {
        doSomethingInternal(mandantPK);
      } catch (Exception e) {
        logExceptionFuerMandant(mandantPK, e);

        throw e;
      }
    }
  }

  protected abstract void doSomethingInternal(MandantPK mandantPK);

  protected Mandant getMandant(MandantPK mandantPK) {
    return mandantBackgroundServiceHelper.getMandant(mandantPK);
  }
}
