package com.ftinc.si.assist.test.js;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.ftinc.si.assist.test.TestLogger;
import com.ftinc.si.assist.test.Tool;

public class JSDefaultDriver implements JSDriver {
	private ScriptEngine m_engine = null;


	@Override
	public boolean load(HashMap<String, Object> map) {
		if (m_engine == null) {
	        ScriptEngineManager manager = new ScriptEngineManager();
	        m_engine = manager.getEngineByName("JavaScript");
		}
		@SuppressWarnings("unchecked")
		ArrayList<String> flist = (ArrayList<String>)map.get("includes");

		for (int i = 0; i < flist.size(); i++) {
			try {
				m_engine.eval(new FileReader(Tool.convert2Alias(flist.get(i))));
			} catch (FileNotFoundException | ScriptException e) {
				TestLogger.err(flist.get(i) + " >>" + e.getMessage());
				return false;
			}
		}
		return true;
	}

	@Override
	public boolean execute(String str) {
		try {
			Object xret = m_engine.eval(str);
			if (str.startsWith("if")) {
				//評価式の場合
				if (xret == null || xret.toString().equals("false")) {
					return false;
				}
			}
		} catch (ScriptException e) {
			TestLogger.err("Execution Failed:" + str + " >>" + e.getMessage());
			return false;
		}
		return true;
	}

	@Override
	public void quit() {
		// TODO 自動生成されたメソッド・スタブ
	}

	@Override
	public void reset() {
		//情報をクリアするため、スクリプトエンジンを再構成する。
        ScriptEngineManager manager = new ScriptEngineManager();
        m_engine = manager.getEngineByName("JavaScript");
	}
}
