/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.myfaces.orchestra.requestParameterProvider.jsf;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.myfaces.orchestra.lib.jsf.ExternalContextUtils;
import org.apache.myfaces.orchestra.requestParameterProvider.RequestParameterResponseWrapper;
import org.apache.myfaces.orchestra.requestParameterProvider.RequestParameterServletFilter;

/**
 * Ensure that a custom wrapper is put around the HttpServletResponse so that encodeURL can be 
 * intercepted and modified.
 * <p>
 * There is a servlet filter (RequestParameterServletFilter) that does this in the obvious way, but
 * it is a nuisance to have to set up filters in the web.xml. This class implements a sneaky hack
 * to get this to happen automatically for JSF applications, ie no servlet filter is needed when
 * this is specified in the faces-config.xml file as the FacesContextFactory.
 * <p>
 * If you have to deal with a mixed environment e.g. JSP/JSF it would be better to use the
 * {@link org.apache.myfaces.orchestra.requestParameterProvider.RequestParameterServletFilter}.
 */
public class RequestParameterFacesContextFactory extends FacesContextFactory
{
    private final FacesContextFactory original;

    public RequestParameterFacesContextFactory(FacesContextFactory original)
    {
        this.original = original;
    }

    /**
     * Invokes the getFacesContext method on the original factory in order to return a
     * perfectly normal FacesContext instance. However the ServletResponse object passed
     * to that FacesContext instance is a modified one that tweaks every url that is
     * processed by the ServletResponse.encodeUrl method.
     */
    public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
    throws FacesException
    {
        if (!ExternalContextUtils.getRequestType(context, request).isPortlet())
        {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            
            // Wrap this request only if something else (eg a RequestParameterServletFilter)
            // has not already wrapped it.
            if (!Boolean.TRUE.equals(httpServletRequest.getAttribute(
                    RequestParameterServletFilter.REQUEST_PARAM_FILTER_CALLED)))
            {
                // No servlet filter has wrapped the response, so do it now for the response
                // referenced by this FacesContext. Note that this wrapper will therefore
                // apply to all output generated via the FacesContext, but not to anything
                // that might be written by filters etc.
                response = new RequestParameterResponseWrapper((HttpServletResponse) response);

                // We now need to reassure the RequestParameterProviderManager that the response has indeed been
                // wrapped; it checks and reports an error if not as it is easy to stuff up this configuration.
                //
                // However we can not just set the REQUEST_PARAMETER_FILTER_CALLED flag here. If code creates its own
                // FacesContext instance for any reason while a request is running, then this method is called again.
                // On the second call this flag would already be set and the response would not be wrapped as required.
                //
                // Therefore we have two separate flags; RequestParameterProviderManager checks whether either
                // REQUEST_PARAM_FILTER_CALLED or REQUEST_PARAM_RESPONSE_WRAPPED has been set.

                httpServletRequest.setAttribute(
                    RequestParameterServletFilter.REQUEST_PARAM_RESPONSE_WRAPPED, Boolean.TRUE);

            }
        }

        return original.getFacesContext(context, request, response, lifecycle);
    }
}
