package de.ivu.elect.jee.presentation.menu;

import java.io.Serializable;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

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

@RequestScoped
public class JSessionMenuBuilder implements Serializable {

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

  private String jseesionId = null;

  public String getJsessionId() {
    // WASDE-1546 http und "secure" führt dazu, dass die sessionId als URL Parameter notwendig ist

    if (jseesionId == null) {
      jseesionId = buildJsessionId();
    }
    return jseesionId;
  }

  private String buildJsessionId() {
    if (isCookieSecureOnly()) {
      try {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExternalContext ectx = fctx.getExternalContext();
        if ("http".equalsIgnoreCase(ectx.getRequestScheme())) {
          HttpSession session = (HttpSession) ectx.getSession(false);
          return ";jsessionid=" + session.getId();
        }
      } catch (Exception e) {
        LOG.warn("SessionId kann nicht ermittelt werden: " + e.getMessage());
      }
    }
    return "";
  }

  protected boolean isCookieSecureOnly() {
    return SessionIdConfigurationStore.SECURE.get();
  }
}
