/* $Id: ScriptEngineBuilder.java,v 1.1 2007/11/21 02:49:47 nito Exp $
 *
 * Copyright (c)ARGO 21, Corporation. 2007.  All rights reserved.
 */
package jp.co.argo21.nautica.workflow.script;

import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

import org.apache.log4j.Logger;

import jp.co.argo21.nautica.workflow.engine.LogManager;
import jp.co.argo21.nautica.workflow.engine.SystemChecker;

public class ScriptEngineBuilder
{
	/** エンジンログ */
	private static Logger eLog = LogManager.getEngineLogger();
	
	private static final ScriptEngineBuilder singleton =
		new ScriptEngineBuilder();
	
	private static final String PREFIX = "nautica.workflow.script.engine";
	
	private ScriptEngineManager sem;

	public static ScriptEngineBuilder getInstance()
	{
		return singleton;
	}
	
	private ScriptEngineBuilder()
	{
		sem = new ScriptEngineManager();
	}

	public ScriptEngine getEngineByName(String shortName)
	{
		ScriptEngine engine = sem.getEngineByName(shortName);
		
		if (engine == null) {
			ScriptEngineFactory factory = searchFactory(shortName);
			if (factory != null) {
				engine = factory.getScriptEngine();
			}
		}
		return engine;
	}

	public void registerEngineName(String name, ScriptEngineFactory factory)
	{
		sem.registerEngineName(name, factory);
	}

	private synchronized ScriptEngineFactory searchFactory(String shortName)
	{
		if (shortName == null) return null;
		
		String key = PREFIX + "." + shortName;
		String factoryName = SystemChecker.getProperty(key);
		ScriptEngineFactory factory = null;
		try {
			factory = (ScriptEngineFactory)Class.forName(factoryName).newInstance();

			if (eLog.isDebugEnabled()) {
				eLog.debug("== Found new script engine factory.  ===");
				eLog.debug("EngineName: " + factory.getEngineName());
				eLog.debug("EngineVersion: " + factory.getEngineVersion());
				eLog.debug("LanguageName: " + factory.getLanguageName());
				eLog.debug("LanguageVersion" + factory.getLanguageVersion());
				List<String> names = factory.getNames();
				for (String name : names) {
					eLog.debug("ShortName: " + name);
				}
				List<String> mimeTypes = factory.getMimeTypes();
				for (String mimeType : mimeTypes) {
					eLog.debug("MimeType: " + mimeType);
				}
				List<String> extensions = factory.getExtensions();
				for (String extension : extensions) {
					eLog.debug("Extension: "+ extension);
				}
				eLog.debug("========================================");
			}
			
			registerEngineName(shortName, factory);
		} catch (Exception ex) {
			factory = null;
		}
		return factory;
	}
}
