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

import java.util.ArrayList;
import java.util.Collection;

import javax.naming.InitialContext;
import javax.naming.NamingException;

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

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


import static java.util.Arrays.asList;

public abstract class AbstractKonfiguration implements KonfigurationBase, CustomParameter<ElectSystemMandantKonfigurationWerte> {

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


  private static final long serialVersionUID = 1L;

  public AbstractKonfiguration() {
    super();
  }

  @Override
  public Collection<ElectSystemMandantKonfigurationWerte> getTemplates() {
    ArrayList<ElectSystemMandantKonfigurationWerte> result = new ArrayList<>();
    result.addAll(asList(ElectKonfigurationWerte.values()));
    result.addAll(asList(MandantKonfigurationWerte.values()));
    return result;
  }

  @Override
  public void setKey(String key) {
    setSchluessel(key);
  }

  @Override
  public String getKey() {
    return getSchluessel();
  }

  /** Beginn ELECT-7826 */
  static {
    setzeJsfDevelopementJndi();
  }

  private static void setzeJsfDevelopementJndi() {
    String stage = "Production";
    if (isForceProduction()) {
      LOG.info("Production-Stage forciert");
    } else {
      if (isDevelopmentMarkerVorhanden()) {
        stage = "Development";
        DevelopmentStore.setDevelopmentStage(true);
      }
    }
    LOG.info("Setze JNDI JSF-Projectstage: " + stage);
    try {
      new InitialContext().bind("java:/env/jsf/ProjectStage", stage);
    } catch (NamingException e) {
      LOG.info("JNDI JSF-Projectstage kann nicht gesetzt werden - schon vorhanden?: " + e.getMessage());
      try {
        new InitialContext().rebind("java:/env/jsf/ProjectStage", stage);
        LOG.info("JNDI JSF-Projectstage kann nicht gesetzt werden - rebind ok");
      } catch (NamingException e2) {
        LOG.info("JNDI JSF-Projectstage kann nicht erneut gesetzt werden : " + e2.getMessage());
      }
    }
  }

  private static boolean isForceProduction(){
    return Boolean.TRUE.toString().equalsIgnoreCase(System.getProperty("de.ivu.elect.ForceProduction"));
  }

  private static boolean isDevelopmentMarkerVorhanden() {
    return Boolean.TRUE.toString().equalsIgnoreCase(System.getProperty("de.ivu.elect.DevelopmentMarker")) || isDevelopmentClassPresent();
  }

  private static boolean isDevelopmentClassPresent() {
    try {
      return Class.forName("de.ivu.elect.DevelopmentMarker", false, Thread.currentThread().getContextClassLoader()) != null;
    } catch (Exception e) {
      return false;
    }
  }

  /** Ende ELECT-7826 */

}
