/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 *  $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.cdi.weld.internal.jsf;

import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.application.ViewHandler;
import javax.faces.lifecycle.LifecycleFactory;

import org.jboss.weld.environment.servlet.jsf.WeldApplication;
import org.jboss.weld.jsf.ConversationAwareViewHandler;
import org.jboss.weld.jsf.WeldPhaseListener;
import org.ow2.util.execution.ExecutionResult;
import org.ow2.util.execution.IExecution;
import org.ow2.util.execution.helper.RunnableHelper;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * A customizer for faces applications.
 *
 * @author Loic Albertin
 */
public class FacesApplicationCustomizer {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(FacesApplicationCustomizer.class);

    /**
     * Utility class
     */
    private FacesApplicationCustomizer() {
    }

    /**                                                        s
     * Customize the Faces application for a given webapp:
     * <ul>
     * <li>It replaces the actual {@link Application} by a {@link WeldApplication} which wrap it</li>
     * <li>It replaces the actual {@link ViewHandler} by a {@link ConversationAwareViewHandler} which wrap it</li>
     * <li>It adds a {@link WeldPhaseListener}</li>
     * </ul>
     *
     * @param classLoader
     * @param webappName
     */
    public static void customizeFacesApplication(ClassLoader classLoader, String webappName) {
        // execute this in the context of the webapp class loader
        IExecution<Void> execution = new IExecution<Void>() {
            public Void execute() throws Exception {
                ApplicationFactory applicationFactory = (ApplicationFactory)
                        FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
                Application delegateApp = applicationFactory.getApplication();
                if (delegateApp != null) {
                    WeldApplication weldApplication = new WeldApplication(delegateApp);
                    ViewHandler currentHandler = weldApplication.getViewHandler();
                    weldApplication.setViewHandler(new ConversationAwareViewHandler(currentHandler));
                    applicationFactory.setApplication(weldApplication);
                }
                LifecycleFactory factory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
                // Maybe the JSF implementation is not installed
                if (factory != null) {
                    javax.faces.lifecycle.Lifecycle lc = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
                    lc.addPhaseListener(new WeldPhaseListener());
                }
                return null;
            }
        };
        ExecutionResult<Void> result = new RunnableHelper<Void>().execute(classLoader, execution);
        if (result.hasException()) {
            logger.debug("The current Webapp {0} is not JSF-enabled", webappName, result.getException());
        }
    }
}
