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

import java.io.File;
import java.lang.reflect.Method;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.Rule;
import org.huihoo.willow.Context;
import org.huihoo.willow.EngineDeployer;
import org.huihoo.willow.Engine;
import org.huihoo.willow.core.StandardEngine;
import org.xml.sax.Attributes;

/**
 * @author reic
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class SetAppBaseRule extends Rule
{

	// ----------------------------------------------------------- Constructors

	/**
	 * Construct a new instance of this Rule.
	 *
	 * @param digester Digester we are associated with
	 */
	public SetAppBaseRule(Digester digester)
	{

		super(digester);

	}

	// ----------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Public Methods

	/**
	 * Handle the beginning of an XML element.
	 *
	 * @param attributes The attributes of this element
	 *
	 * @exception Exception if a processing error occurs
	 */
	public void begin(Attributes attributes) throws Exception
	{
		Context child = (Context) digester.peek(0);
		EngineDeployer parent = (EngineDeployer) digester.peek(1);
		Engine engine = null;
		if (!(parent instanceof StandardEngine))
		{
			Method method = parent.getClass().getMethod("getEngine", null);
			engine = (Engine) method.invoke(parent, null);
		}
		else
		{
			engine=(Engine)parent;
		}

		File engineBase =engine.getAbsoluteEngineBase();

		String appBase = child.getAppBase();
		if (appBase == null)
		{
			// Trying to guess the appBase according to the name
			String name = child.getName();
			if (name == null)
			{
				return;
			}
			
			appBase = name;
		}

		File file = new File(appBase);
		if (!file.isAbsolute())
		{
			appBase = (new File(engineBase, appBase)).getCanonicalPath();
		}
		else
		{
			appBase = file.getCanonicalPath();
		}

		//olny file system based on directory is be supported
		File appDir = new File(appBase);
		if (!appDir.exists())
		{
			return;
		}

		if (appBase.startsWith(engineBase.getPath()))
		{
			//if appbase in enginebase ,use relative path
			appBase = appBase.substring(engineBase.getPath().length() + 1);
		}
		
		//get relative pathname
		appBase = appBase.replace(File.separatorChar, '/');

		child.setAppBase(appBase);

	}

}
