package hc.adl;

import java.util.Map;
import java.util.Vector;

/**
 * Built-in functions
 * 
 * @author hc
 */
public class ADLFunctions {

	/**
	 * Call a function
	 * 
	 * @param builtin
	 *            function to call
	 * @param params
	 *            function parameters
	 * @return function result.
	 */
	public static Object CallFunction(EquationParser parser,
			Map<String, Object> locals, EFunction builtin, Vector<Object> params) {
		switch (builtin) {
		case Format:
			return Format(params);
		case Log:
			return Log(params);
		case Deref:
			return Deref(parser, locals, params);
		case IsNull:
			return new Boolean(params.get(0) == null);
		}
		return null;
	}

	private static Object Deref(EquationParser parser,
			Map<String, Object> locals, Vector<Object> params) {
		if (locals.containsKey((String) params.get(0))) {
			return locals.get((String) params.get(0));
		} else {
			return parser.GetVariable((String) params.get(0));
		}
	}

	/**
	 * Logger.debug wrapper
	 * 
	 * @param params
	 *            String to log
	 * @return zero on success
	 */
	private static Object Log(Vector<Object> params) {
		System.out.println("ScriptLog: " + ((Object) params.get(0)).toString());
		return new Integer(0);
	}

	/**
	 * System.format wrapper
	 * 
	 * @param params
	 *            System.format params
	 * @return System.format result
	 */
	private static Object Format(Vector<Object> params) {
		return String.format((String) params.get(0), params.subList(1,
				params.size()).toArray());
	}
}
