/*
 * Created on 2004/11/09
 */
package org.seasar.tapestry;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tapestry.ApplicationServlet;
import org.apache.tapestry.IEngine;
import org.apache.tapestry.engine.BaseEngine;
import org.apache.tapestry.request.RequestContext;
import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
import org.seasar.framework.util.StringUtil;
import org.seasar.tapestry.engine.S2Engine;

/**
 * @author maruo_syunsuke
 * @object-type UserObject
 */
public class S2TapestryServlet extends ApplicationServlet {
	public static final String CONFIG_PATH_KEY = "configPath";
    
	public void init() throws ServletException {
		initS2Container();
		super.init();
	}

	private void initS2Container() {
		String configPath = null;
		ServletConfig servletConfig = getServletConfig();
		if( servletConfig != null ){
			configPath = servletConfig.getInitParameter( CONFIG_PATH_KEY );
		}
		if( !StringUtil.isEmpty( configPath ) ){
			SingletonS2ContainerFactory.setConfigPath( configPath );
		}
		SingletonS2ContainerFactory.setServletContext( getServletContext() );
		SingletonS2ContainerFactory.init();
	}

	public void destroy() {
		super.destroy();
		SingletonS2ContainerFactory.destroy();
	}

	public static S2Container getContainer() {
		return SingletonS2ContainerFactory.getContainer();
	}

	protected void doService( HttpServletRequest request,
								HttpServletResponse response )
			throws IOException, ServletException {
		S2Container container = S2TapestryServlet.getContainer();
		container.setRequest( request );
		container.setResponse( response );
		super.doService( request, response );
	}

	/**
     * XXX Tapestryの設定ファイルでIEngineを指定する場合、コンテナに登録しないでください。
	 * default engine is S2Engine
	 */
    protected IEngine createEngine(RequestContext context) throws ServletException{
        S2Container container = S2TapestryServlet.getContainer();
        if( container.hasComponentDef(IEngine.class) ){
            return (IEngine)container.getComponent(IEngine.class);
        }
        return super.createEngine(context);
    }
    protected String getEngineClassName() {
        String engineClassName = super.getEngineClassName();
        if( engineClassName.equals( BaseEngine.class.getName() ) ){
            engineClassName = S2Engine.class.getName();
        }
        return engineClassName;
    }
}
