/*
 * Copyright 2009-2010 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.awk.nano.java6;

import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import net.morilib.awk.nano.AwkException;
import net.morilib.awk.nano.expr.AwkExpression;
import net.morilib.awk.nano.io.AwkFiles;
import net.morilib.awk.nano.value.AwkValue;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2014/02/19
 */
public class AwkCompiledScript extends CompiledScript {

	//
	private AwkExpression prog;
	private AwkScriptEngine engine;

	//
	AwkCompiledScript(AwkExpression prg, AwkScriptEngine eng) {
		prog   = prg;
		engine = eng;
	}

	/* (non-Javadoc)
	 * @see javax.script.CompiledScript#eval(javax.script.ScriptContext)
	 */
	@Override
	public Object eval(ScriptContext context) throws ScriptException {
		AwkFiles f = new AwkFiles(context.getReader(),
				context.getWriter(), context.getErrorWriter());
		AwkValue r;

		try {
			r = prog.eval(((AwkScriptContext)context).engine, f);
			return r.toObject();
		} catch(AwkException e) {
			throw new ScriptException(e);
		}
	}

	/* (non-Javadoc)
	 * @see javax.script.CompiledScript#getEngine()
	 */
	@Override
	public ScriptEngine getEngine() {
		return engine;
	}

}
