/*
 * Created on 2004-7-20
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.huihoo.willow.tomcat;

import java.lang.reflect.Method;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.huihoo.willow.client.WorkflowClientFactoryImpl;

import workflow.client.MatrixClient;

/**
 * @author reic
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class TomcatHostLifecycleListener implements LifecycleListener
{
	/**
		 * Process the AFTER_START_EVENT event for an associated Context.
		 *
		 * @param event The lifecycle event that has occurred
		 */
	public void lifecycleEvent(LifecycleEvent event)
	{
		if (event.getType().equals(Lifecycle.AFTER_START_EVENT))
		{
			try
			{
				afterStart(event.getLifecycle());
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}

	}
	
	/**
	 * Process a "start" event for this Host - in background
	 */
	private synchronized void afterStart(Object host)
	throws Exception 
	{
		Method method = null;
		
		method = host.getClass().getMethod("findChildren", null);
		Object[] contexts=(Object[])method.invoke(host, null);

		if(contexts==null)
		{
			return;
		}

		for(int k=0;k<contexts.length;++k)
		{
			Object context=contexts[k];

			method = context.getClass().getMethod("getName", null);
			method = context.getClass().getMethod("getServletContext", null);
			Object servletContext=method.invoke(context,null);

			Class paramTypes[] = {String.class,Object.class};
			Object paramValues[] = new Object[2];
			paramValues[0]=MatrixClient.INITIAL_CLIENT_FACTORY;
			paramValues[1]=new WorkflowClientFactoryImpl();

			method = servletContext.getClass().getMethod("setAttribute", paramTypes);
			method.invoke(servletContext,paramValues);
		}
	}
}
