
package de.ivu.elect.jee.startup;

import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.inject.Inject;

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

import de.ivu.elect.jee.exception.SystemExceptionWriter;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class PostStartupAsyncRunner {

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

  private static final long TIMEOUT_IN_MSC = 5 * 1000; // Zehn Sekunden

  @Inject
  private transient PostStartupFinder postStartupFinder;

  @Inject
  private transient SystemExceptionWriter systemExceptionWriter;

  @Resource
  protected transient TimerService timerService;

  public void createTimer() {
    LOG.info("Post startup async - create Timer");
    timerService.createSingleActionTimer(TIMEOUT_IN_MSC, new TimerConfig("", false));
    LOG.info("startup async done - timer created");

  }

  @Timeout
  public void handleTimer(Timer timer) {
    LOG.info("Post startup async - timeout");
    for (PostStartupAsync postStartupAsync : postStartupFinder.getPostStartupsAsync()) {
      try {
        postStartupAsync.postStartup();
      } catch (Exception e) {
        systemExceptionWriter.writeSystemException("PostStartupAsync Fehler: " + postStartupAsync, e);
      }
    }
    LOG.info("Post startup async - timeout done");
  }

}
