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 JythonEngineGBean
implements GBeanLifecycle
{
	public static GBeanInfo GBEAN_INFO;
	
	public static final String PYTHON_PATH = "python.path";
	public static final String PYTHON_CACHE_DIR = "python.cachedir";

	private String path;
	private String cacheDirectory;

	static {
		GBeanInfoBuilder builder =
			new GBeanInfoBuilder("JythonEngineGBean", JythonEngineGBean.class);
		builder.addAttribute("path", String.class, true);
		builder.addAttribute("cacheDirectory", String.class, true);
		GBEAN_INFO = builder.getBeanInfo();
	}

	public static GBeanInfo getGBeanInfo()
	{
		return GBEAN_INFO;
	}

	public void doStart() throws Exception
	{
		System.setProperty(PYTHON_PATH, path);
		System.setProperty(PYTHON_CACHE_DIR, cacheDirectory);
	}

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

	public void doFail()
	{
	}

	public String getCacheDirectory()
	{
		return cacheDirectory;
	}

	public void setCacheDirectory(String cacheDirectory)
	{
		this.cacheDirectory = parsePath(cacheDirectory);
	}

	public String getPath()
	{
		return path;
	}

	public void setPath(String path)
	{
		this.path = parsePath(path);
	}
	
	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();
	}
}
