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

 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.ArrayList;
import java.util.Stack;

import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.LogicalFn.LogicalFnType;


/**
 * Encapsulates the Math.random() function.
 */
public class Random extends PostfixMathCommand {
	
	java.util.Random rand = new java.util.Random();
	
	public Random() {
		numberOfParameters = -1;

	}

	@Override
	public void run(Stack stack) throws ParseException {
		checkStack(stack);// check the stack
		
		if(curNumberOfParameters > 2) throw new ParseException("Random() takes 0 to 2 parameters.");
		
		if(curNumberOfParameters == 0) {
			
			stack.push(new Double(rand.nextDouble()));	
			
		}else		
		if(curNumberOfParameters == 1) {
			
			Object arg = stack.pop();
			
			if(arg instanceof Number) {
				if(arg instanceof Double)
					stack.push(new Integer(rand.nextInt((int) Math.round((Double) arg))));
				else if(arg instanceof Float)
					stack.push(new Integer(rand.nextInt(Math.round((Float) arg))));
				else if(arg instanceof Integer)
					stack.push(new Integer(rand.nextInt((Integer) arg)));
				else if(arg instanceof Long)
					stack.push(new Integer(rand.nextInt(Math.round((Long) arg))));
				else 
					throw new ParseException("Random() canẗ work with "+arg.getClass().getSimpleName());
			}
			return;			
			
		}

		return;
	}
}
