package com.eactive.eai.transformer.function.generic;

import java.util.Stack;

import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;


public class Substring extends PostfixMathCommand {
    public Substring() {
        numberOfParameters = -1;
    }

    public void run(Stack inStack) throws ParseException {
        checkStack(inStack);

        if (curNumberOfParameters == 3) {
            Object p3 = inStack.pop();
            if (p3 instanceof Number) {
	            int _p3 = ((Number) p3).intValue();
	            Object p2 = inStack.pop();	
	            if (p2 instanceof Number) {
	                int _p2 = ((Number) p2).intValue();
	                Object p1 = inStack.pop();
	                if (p1 instanceof String) {
	                    String str = (String) p1;
	
	                    if (_p2 > _p3) {
	                        throw new ParseException(
	                            "invalid operation : substring(\"" + str + "\"" +
	                            ", beginIndex=" + _p2 + 
	                            ", endIndex=" +_p3 + ") - endIndex must be greater than beginIndex");
	                    }
	
	                    inStack.push(str.substring(_p2, _p3));
	                } else if (p1 instanceof byte[]) {
	                    String str = new String((byte[]) p1);
	
	                    if (_p2 > _p3) {
	                        throw new ParseException(
	                            "Invalid Operation : substring(\"" + str + "\"," +
	                            _p2 + "," + _p3 + ")");
	                    }
	
	                    inStack.push(str.substring(_p2, _p3));
	                } else {
	                    throw new ParseException("Invalid parameter type, p1 is not string/bytes");
	                }
	            } else {
	                throw new ParseException("Invalid parameter type, p2 is not number");
	            }
	        } else {
	            throw new ParseException("Invalid parameter type, p3 is number");
	        }
        } else if (curNumberOfParameters == 2) {
            Object p2 = inStack.pop();
            if (p2 instanceof Number) {
                int _p2 = ((Number) p2).intValue();
                Object p1 = inStack.pop();

                if (p1 instanceof String) {
                    String str = (String) p1;
                    inStack.push(str.substring(_p2));
                } else if (p1 instanceof byte[]) {
                    String str = new String((byte[]) p1);
                    inStack.push(str.substring(_p2));
                } else {
                    throw new ParseException("Invalid parameter type, p1 is not string/bytes");
                }
            } else {
                throw new ParseException("Invalid parameter type, p2 is not number");
            }       	
        } else {
            throw new ParseException("invalid parameter count : " + curNumberOfParameters + " - parameter count must be 2 or 3");
        }
    }
}
