package jp.co.argo21.nautica.workflow.management.gbean;

import java.util.StringTokenizer;

import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.gbean.GBeanLifecycle;

public class JRubyEngineGBean
implements GBeanLifecycle
{
	public static GBeanInfo GBEAN_INFO;
	
	public static final String JRUBY_PATH = "com.sun.script.jruby.loadpath";

	private String loadPath;

	static {
		GBeanInfoBuilder builder =
			new GBeanInfoBuilder("JRubyEngineGBean", JRubyEngineGBean.class);
		builder.addAttribute("loadPath", String.class, true);
		GBEAN_INFO = builder.getBeanInfo();
	}

	public static GBeanInfo getGBeanInfo()
	{
		return GBEAN_INFO;
	}

	public void doStart() throws Exception
	{
		System.setProperty(JRUBY_PATH, loadPath);
	}

	public void doStop() throws Exception
	{
		System.clearProperty(JRUBY_PATH);
	}

	public void doFail()
	{
	}

	public String getLoadPath()
	{
		return loadPath;
	}

	public void setLoadPath(String loadPath)
	{
		this.loadPath = parsePath(loadPath);
	}
	
	private String parsePath(String path)
	{
		if (path == null) return null;
		
		String baseDir = System.getProperty("org.apache.geronimo.base.dir");
		String separator = System.getProperty("file.separator");
		StringBuilder sb = new StringBuilder();
		StringTokenizer st = new StringTokenizer(path, ":", true);
		while (st.hasMoreTokens()) {
			String p = st.nextToken();
			if (p.trim().equals("")) continue;

			if (!(p.equals(":") || p.startsWith(separator))) {
				p = baseDir + separator + p;
			}
			sb.append(p);
		}
		
		return sb.toString();
	}
}
