/*
 * 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.lib.jsf;

import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.myfaces.orchestra.CoreConfig;
import org.apache.myfaces.orchestra.frameworkAdapter.FrameworkAdapter;
import org.apache.myfaces.orchestra.frameworkAdapter.jsf.JsfFrameworkAdapter;

/**
 * RequestHandler that ensures that the FrameworkAdapter is initialised as a JsfFrameworkAdapter.
 * 
 * @since 1.1
 */
class FrameworkAdapterRequestHandler implements RequestHandler
{
    private final static String CONVERSATION_MESSAGER_CLASS =
        "org.apache.myfaces.orchestra.CONVERSATION_MESSAGER"; // NON-NLS

    private final Log log = LogFactory.getLog(FrameworkAdapterRequestHandler.class);

    private JsfFrameworkAdapter adapter;

    public void init(FacesContext facesContext) throws FacesException
    {
        log.debug("init");

        if (FrameworkAdapter.getCurrentInstance() == null)
        {
            log.debug("creating jsfFrameworkAdapter");
            // No filter has yet initialised the adapter, so do it here.
            String conversationMessagerClass = getConversationMessagerClass(facesContext);
            adapter = new JsfFrameworkAdapter(conversationMessagerClass);
            adapter.beginRequest();
        }
    }

    public void deinit() throws FacesException
    {
        if (adapter != null)
        {
            adapter.endRequest();
        }
    }
    
    private static String getConversationMessagerClass(FacesContext facesContext)
    {
        ExternalContext ec = facesContext.getExternalContext();

        String cn = ec.getInitParameter(CONVERSATION_MESSAGER_CLASS);
        if (cn != null)
        {
            return cn;
        }
        
        cn = ec.getInitParameter(CoreConfig.CONVERSATION_MESSAGER);
        return cn;
    }
}
