/********************************
 *	프로젝트 : gargoyle-nashorn
 *	패키지   : com.kyj.fx.nashorn.exec
 *	작성일   : 2019. 9. 23.
 *	작성자   : KYJ (callakrsos@naver.com)
 *******************************/
package com.kyj.fx.nashorn.exec;

import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

import javax.script.ScriptException;

import com.kyj.fx.nashorn.DefaultScriptEngine;
import com.kyj.fx.nashorn.entires.Nashorn;

/**
 * @author KYJ (callakrsos@naver.com)
 *
 */
public class NashornExec {
	
	/**
	 * @최초생성일 2019. 9. 23.
	 */
	private Nashorn nashorn;

	
	/**
	 * @param nashorn
	 */
	public NashornExec(Nashorn nashorn) {
		super();
		this.nashorn = nashorn;
	}

	/**
	 * @작성자 : KYJ (callakrsos@naver.com)
	 * @작성일 : 2019. 9. 23. 
	 * @return
	 * @throws NoSuchMethodException
	 * @throws IOException
	 * @throws ScriptException
	 */
	public Object run() throws NoSuchMethodException, IOException, ScriptException {
		DefaultScriptEngine engine = new DefaultScriptEngine();
		return engine.invokeFunction(readScript(), getMainFunction(), getArguments());
	}
	
	/**
	 * @작성자 : KYJ (callakrsos@naver.com)
	 * @작성일 : 2019. 9. 23. 
	 * @return
	 * @throws IOException
	 */
	public String readScript() throws IOException {
		return this.nashorn.getNashornScript().getContent();
	}
	
	/**
	 * @작성자 : KYJ (callakrsos@naver.com)
	 * @작성일 : 2019. 9. 23. 
	 * @return
	 * @throws IOException
	 */
	public String getMainFunction() throws IOException {
		return this.nashorn.getNashornScript().getMainFunction();
	}
	
	/**
	 * @작성자 : KYJ (callakrsos@naver.com)
	 * @작성일 : 2019. 9. 23. 
	 * @return
	 */
	public Map<String,String> getArguments() {
		return this.nashorn.getNashornParams().stream()
				.collect(Collectors.toMap(v -> v.getName(), v -> v.getValue()));
	}
	
}
