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

import com.eactive.eai.common.context.ElinkTransactionContext;
import org.apache.commons.lang.StringUtils;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;

import java.util.Stack;

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

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

        String bizData = ElinkTransactionContext.getRequestBizData();

        Object p1 = inStack.pop();
        Object p2 = inStack.pop();

        int start = toInt(p2);
        int end = toInt(p1);

        String resultStr = bizData.substring(start, end);
        inStack.clear();

        inStack.push(resultStr);
    }

    public static int toInt(Object obj) {
        if (obj instanceof Number) {
            return ((Number) obj).intValue();
        }
        if (obj instanceof String) {
            return Integer.parseInt(((String) obj).trim());
        }
        throw new IllegalArgumentException("Cannot convert to int: " + obj);
    }
}
