/*****************************************************************************

 JEP 2.4.1, Extensions 1.1.1
      April 30 2007
      (c) Copyright 2007, Nathan Funk and Richard Morris
      See LICENSE-*.txt for license information.

 *****************************************************************************/

package org.nfunk.jep.function;


import java.util.Stack;

import org.nfunk.jep.ParseException;


public class LogicalFn extends PostfixMathCommand {
	
	public enum LogicalFnType{
		AND,NAND,OR,NOR,XOR,NXOR,ODD,EVEN;
	}
	
	LogicalFnType type;
	

	public LogicalFn(LogicalFnType id_in) {
		type = id_in;
		numberOfParameters = -1;
	}

	@Override
	public void run(Stack inStack) throws ParseException {
		checkStack(inStack);// check the stack
		
		if (curNumberOfParameters < 2 && type != ODD && type != EVEN) throw new ParseException("Not enough arguments for ");

		// initialize the result to the first argument
		Object sum = stack.pop();
		Object param;
		int i = 1;

		// repeat summation for each one of the current parameters
		while (i < curNumberOfParameters) {
			// get the parameter from the stack
			param = stack.pop();

			// add it to the sum (order is important for String arguments)
			sum = addFun.add(param, sum);

			i++;
		}

		// push the result on the inStack
		stack.push(sum);
		
		

		Object param2 = inStack.pop();
		Object param1 = inStack.pop();

		double x, y;
		if ((param1 instanceof Number))
			x = ((Number) param1).doubleValue();
		else if ((param1 instanceof Boolean))
			x = ((Boolean) param1).booleanValue() ? 1.0 : 0.0;
		else
			throw new ParseException("Logical: require a number or Boolean value on left, have " + param1.getClass().getName());
		if ((param2 instanceof Number))
			y = ((Number) param2).doubleValue();
		else if ((param2 instanceof Boolean))
			y = ((Boolean) param2).booleanValue() ? 1.0 : 0.0;
		else
			throw new ParseException("Logical: require a number or Boolean value on right, have " + param1.getClass().getName());

		int r;
		
		boolean a = (x != 0d),b = (y != 0d),out=false;


		
		r = out?1:0;
		
		inStack.push(new Double(r)); // push the result on the inStack
		return;
	}
}
