
package de.ivu.elect.jee.faces.context;

import static org.apache.commons.lang3.StringUtils.isAllBlank;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextWrapper;

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

/**
 * https://insights2jsf.wordpress.com/2009/07/03/using-custom-factories-or-howto-wrap-facescontext/
 */
public class ElectFacesContext extends FacesContextWrapper {

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

  private final FacesContext wrapped;

  private final ExternalContext externalContext;

  public ElectFacesContext(FacesContext context) {
    this.wrapped = context;
    // 1. assign the new FacesContext instance to the ThreadLocal
    setCurrentInstance(this);

    // 2. put CustomFacesContext as FacesContext to ELContext
    getELContext().putContext(FacesContext.class, this);

    // 3. preset wrapping CustomExternalContext
    externalContext = new ElectExternalContext(this.wrapped.getExternalContext());
  }

  @Override
  public FacesContext getWrapped() {
    return wrapped;
  }

  @Override
  public ExternalContext getExternalContext() {
    return externalContext;
  }

  @Override
  public void addMessage(String clientId, FacesMessage message) {
    if (message != null) {
      if (isAllBlank(message.getSummary(), message.getDetail())) {
        LOG.error("FacesMessage OHNE Text ignoriert [clientId = {}, severity = {}, summary = <{}>, detail = <{}>]", clientId, message.getSeverity(),
            message.getSummary(), message.getDetail());
      } else {
        super.addMessage(clientId, message);
      }
    }
  }
}
