package railo.runtime.op;

import railo.runtime.PageContext;
import railo.runtime.interpreter.VariableInterpreter;
import railo.runtime.type.Collection;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.scope.Scope;
import railo.runtime.util.VariableUtilImpl;

public class Elvis {
	
	/**
	 *  called by the Elvis operator from generated bytecode
	 * @param pc
	 * @param scope
	 * @param varNames
	 * @return
	 */
	public static boolean operate(PageContext pc , double scope,Collection.Key[] varNames) {
		return _operate(pc, scope, varNames,0); 
	}

	/**
	 *  called by the Elvis operator from generated bytecode
	 * @param pc
	 * @param scope
	 * @param varNames
	 * @return
	 */
	public static boolean operate(PageContext pc , double scope,String[] varNames) {
		return _operate(pc, scope, KeyImpl.toKeyArray(varNames),0);
	}
	
	/**
	 *  called by the Elvis operator from the interpreter
	 * @param pc
	 * @param scope
	 * @param varNames
	 * @return
	 */
	public static boolean operate(PageContext pc , String[] varNames) {
		int scope = VariableInterpreter.scopeString2Int(varNames[0]);
		return _operate(pc, scope, KeyImpl.toKeyArray(varNames), scope==Scope.SCOPE_UNDEFINED?0:1);
	}
	
	private static boolean _operate(PageContext pc , double scope,Collection.Key[] varNames, int startIndex) {
		Object defVal=null;
		try {
			Object coll =VariableInterpreter.scope(pc, (int)scope, false); 
			//Object coll =pc.scope((int)scope);
			VariableUtilImpl vu = ((VariableUtilImpl)pc.getVariableUtil());
			for(int i=startIndex;i<varNames.length;i++) {
				coll=vu.getCollection(pc,coll,varNames[i],defVal);
				if(coll==defVal)return false;
			}
		} catch (Throwable t) {
	        return false;
	    }
		return true; 
	}
}
