package jp.hasc.hasctool.core.runtime.script;

import java.io.InputStream;
import java.io.InputStreamReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import jp.hasc.hasctool.core.runtime.AbstractRuntimeBean;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.util.CoreUtil;

/**
 * ScriptEngineのwrapperです
 * @author iwasaki
 */
public class ScriptSupport {
	public static final String LANGUAGE_JAVASCRIPT = "javascript";
	private ScriptEngineManager manager_;
	private ScriptEngine engine_;

	public ScriptSupport(String language) {
		manager_ = new ScriptEngineManager();
        engine_ = manager_.getEngineByName(language);
	}

	public ScriptEngine getEngine() {
		return engine_;
	}
	
	public Invocable getInvocable() {
		return (Invocable)engine_;
	}
	
	public void setup(AbstractRuntimeBean host, String scriptFilePath) {
		engine_.put("host", host);
		try {
			InputStream inps = host.getRuntimeContext().getFileStreamProvider().openInputStream(scriptFilePath);
			engine_.eval(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
		} catch (Exception ex) {
			CoreUtil.throwAsRuntimeException(ex);
		}
	}
	
	public Object invokeFunction(String name, Object... args) {
		try {
			return getInvocable().invokeFunction("processMessage", args);
		} catch (Exception ex) {
			CoreUtil.throwAsRuntimeException(ex);
			return null;
		}
	}

}
