package com.eactive.eai.custom.transformer.function.userdefined;

import java.util.Stack;

import org.apache.commons.lang.StringUtils;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;


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

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

        if (curNumberOfParameters == 4) {
            Object p4 = inStack.pop();
            if (p4 instanceof String) {
	            String falseVal = (String) p4;
	            Object p3 = inStack.pop();	
	            if (p3 instanceof String) {
	            	String trueVal = (String) p3;
	                Object p2 = inStack.pop();
	                if (p2 instanceof String) {
	                    String str = (String) p2;
	                    Object p1 = inStack.pop();
	                    if (p1 instanceof String) {
	                    	String originStr = (String) p1;
	                    	if (StringUtils.contains(originStr, str)) {
	                    		inStack.push(trueVal);
	                    	} else {
	                    		inStack.push(falseVal);
	                    	}
	                    } else if (p1 instanceof byte[]) {
	                    	String originStr = new String((byte[]) p1);
	                    	if (StringUtils.contains(originStr, str)) {
	                    		inStack.push(trueVal);
	                    	} else {
	                    		inStack.push(falseVal);
	                    	}
	                    } else {
	                    	throw new ParseException("Invalid parameter type, p1 is not string/bytes");
	                    }
	                } else {
	                	throw new ParseException("Invalid parameter type, p2 is not String");
	                }
	            } else {
	                throw new ParseException("Invalid parameter type, p3 is not String");
	            }
	        } else {
	            throw new ParseException("Invalid parameter type, p4 is String");
	        }
        } else {
            throw new ParseException("invalid parameter count : " + curNumberOfParameters + " - parameter count must be 4");
        }
    }
}
