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

import java.util.Stack;

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

import com.eactive.eai.common.property.PropManager;
import com.initech.inisafenet.KeyFixManager;

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

    public void run(Stack inStack) throws ParseException {
        checkStack(inStack);
           
        Object param = inStack.pop();
        byte[] value = null;
        
        KeyFixManager keyMgr = null;
        byte[] encData = null;
        
        PropManager propManager = PropManager.getInstance();
        String sConf = propManager.getProperty("IniSafeNet","properties.path"); 
        String iniSafeKey = propManager.getProperty("IniSafeNet","key.value"); 

        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;
        } else {
            throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
        }
        
        try {
        	keyMgr = new KeyFixManager(sConf);
        	//encData = keyMgr.encrypt(iniSafeKey, value); 
        	encData = keyMgr.encrypt(value);    
        	inStack.push(encData);
        } catch (Exception e) {
            //throw new ExecutionException(e.getMessage(), parameters, e);
            throw new ParseException(e.getMessage(), e);
        }    	
    }
}
