/*
 * Galatea Dialog Manager:
 * (c)2003 Takuya NISHIMOTO (nishi@hil.t.u-tokyo.ac.jp)
 *
 * $Id: EvaluateCommand.java,v 1.2 2006/11/20 01:13:35 nishi Exp $
 */

package galatea.command;

//import galatea.main.*;
import galatea.dialog.RuntimeError;
import galatea.util.Util;

public class EvaluateCommand extends Command
{
//	private Debug dbg = new Debug("Eval");
	private String str_ = null;
	private String with_ = "";
	
	public EvaluateCommand(String str)
	{
		str_ = str;
	}
	
	public EvaluateCommand(String str, String with)
	{
		str_ = str;
		with_ = with;
	}
	
	public EvaluateCommand(String str, String with, String cond)
	{
		str_ = str;
		with_ = with;
		setCondition(cond);
	}
	
	public String doEvaluate() throws RuntimeError
	{
		if (str_ == null)
			return "null";
		
		String script;
		if ( with_ != null && with_.length() > 0 ) {
			script = "with(" + with_ + "){" + str_ + "}";
		} else {
			script = str_;
		}
		
		return ecmascript_.evaluate(script); 
		
	}
	
	public String toString()
	{
		String s;
		String wt = Util.encodeXmlChars(with_);
		String sc = Util.encodeXmlChars(str_);
		
		if ( with_ != null && with_.length() > 0 ) {
			s = "  <script with=\"" + wt + "\">" + sc + "</script>";
		} else {
			s = "  <script>" + sc + "</script>";
		}
		return s;
	}
	
	public void execute() throws RuntimeError
	{
		if ( evaluateCondition() == true ) {
			doEvaluate();
		}
	}
	
}
