package org.seasar.tapestry.engine;

import ognl.OgnlRuntime;

import org.apache.tapestry.engine.BaseEngine;
import org.apache.tapestry.engine.IEngineService;
import org.apache.tapestry.engine.IPageSource;
import org.apache.tapestry.request.RequestContext;
import org.seasar.framework.container.S2Container;
import org.seasar.tapestry.S2TapestryServlet;
import org.seasar.tapestry.ognl.binder.Binder;
import org.seasar.tapestry.service.InjectionForEngineService;
import org.seasar.tapestry.service.InjectionForEngineService_Null;
import org.seasar.tapestry.util.InjectionUtil;

/**
 * S2Tapestry Engine
 * @author higa
 */
public class S2Engine extends BaseEngine {
	public static final String CONFIG_PATH_KEY = "configPath";
    private InjectionForEngineService _injection = new InjectionForEngineService_Null();

	static{
		OgnlRuntime.setPropertyAccessor(
			Binder.class, new ListenersPropertyAccessor() );
	}

	protected Object createGlobal( RequestContext context ) {
		Object global = super.createGlobal( context );
		return new GlobalProxy( global );
	}

	protected IPageSource createPageSource( RequestContext context ) {
        S2Container container = S2TapestryServlet.getContainer();
        IPageSource pageSource = null ;
        if( container.hasComponentDef(IPageSource.class)){
            pageSource = (IPageSource)container.getComponent(IPageSource.class);
        }
        if( pageSource == null ) pageSource = new S2PageSource( this );
        InjectionUtil.invokeSetterInjection(pageSource);
        return pageSource ;
    }

    public IEngineService getService( String name ) {
        IEngineService engineService = super.getService( name );
		_injection.invoke( engineService );
        return engineService; 
	}

    public InjectionForEngineService getInjection() {
        return this._injection;
    }
    public void setInjection( InjectionForEngineService injection ) {
        if( injection == null ) return ;
        this._injection = injection;
    }
}