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

import javax.faces.application.Application;
import javax.faces.application.ProjectStage;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;

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

import de.ivu.elect.jee.faces.DevelopmentStore;

/**
 * Vorlagen:
 * https://stackoverflow.com/questions/17450370/how-to-get-resource-paths-without-facescontext
 * https://books.google.de/books?id=ABVMDAAAQBAJ&pg=PT89&lpg=PT89&dq=processEvent+SystemEvent&source=bl&ots=GhgKJKRhb0&sig=Avf43Y7zZj8NOqg3lbew-Jvqq9U&hl=de&sa=X&ved=0ahUKEwj22e7chcbaAhWByaQKHdAbDxIQ6AEIQDAD#v=onepage&q=processEvent%20SystemEvent&f=false
 */
public class SystemCheckProjectStageApplicationListener implements SystemEventListener {

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

  @Override
  public void processEvent(SystemEvent event) throws AbortProcessingException {
    if (DevelopmentStore.isDevelopmentStageSet()) {
      LOG.info("DevelopmentStage bereits gesetzt: " + DevelopmentStore.isDevelopmentStage());
    } else {
      try {
        ProjectStage projectStage = ((Application) event.getSource()).getProjectStage();
        LOG.info("ProjectStage: " + projectStage);
        DevelopmentStore.setDevelopmentStage(ProjectStage.Development.equals(projectStage));
      } catch (Exception e) {
        LOG.warn("Fehler beim Bestimmen der DevelopmentStage");
        DevelopmentStore.setDevelopmentStage(false);
      }
    }
  }

  @Override
  public boolean isListenerForSource(Object source) {
    return source instanceof Application;
  }

}
