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

import java.util.Stack;

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

import com.eactive.eai.transformer.function.util.CodeConversion;


/**
 * ASCII 값을 EBCDIC으로 변환하는 함수.
 * 입력 값은 byte[], 결과는 byte[]임.
 */
public class ASCII2EBCDIC9 extends PostfixMathCommand {

    public ASCII2EBCDIC9() {
        numberOfParameters = 2;
    }

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

        Object param2 = inStack.pop();
        int len = ((Number) param2).intValue();  

        Object param = inStack.pop();

        byte[] value = null;

        if (param instanceof String) {
            value = ((String) param).getBytes();
        } else if (param instanceof byte[]) {
            value = (byte[]) param;
        } else if (param instanceof Double) {
        	if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
        		value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
        	} else {
                value =((Number) param).toString().getBytes();
        	}
        } else if (param instanceof Number) {
            value = ((Number) param).toString().getBytes();
        } else if (param == null) {
//            inStack.push(null);
//            return;
        	value = new byte[0];        	
        } else {
            throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
        }        

        try {
            byte[] buff = null;
            
            if(value.length > 0) {
            	buff = CodeConversion.ascToSE9(value, len);
            }
            else {
            	buff = CodeConversion.appendHostZero(value, len);
            }
//            if(len!=buff.length) {
//                System.out.println("########################"+value+"=>"+new String(buff));
//            }
            inStack.push(buff);
        } catch (Exception e) {
            //throw new ExecutionException(e.getMessage(), parameters, e);
            throw new ParseException(e.getMessage(), e);
        }

 
    }
}
