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

import java.io.UnsupportedEncodingException;
import java.util.Stack;

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


/**
 * EUC-KR 값을 UTF-8 로 변환하는 함수.
 * 입력 값은 byte[], 결과는 byte[]임.
 */
public class EUCKR2UTF8 extends PostfixMathCommand {
    public EUCKR2UTF8() {
        numberOfParameters = 1;
    }
    private String sourceChar = "EUC-KR";
    private String targetChar = "UTF-8";

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

        Object param = inStack.pop();

        byte[] value = null;

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

        try {
            inStack.push(new String(value,sourceChar).getBytes(targetChar));
        } catch (Exception e) {
            //throw new ExecutionException(e.getMessage(), parameters, e);
            throw new ParseException(e.getMessage(), e);
        }
    }
}
