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

import java.util.Stack;

import com.eactive.eai.common.context.ElinkTransactionContext;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;

import com.eactive.eai.common.property.PropManager;

import java.nio.charset.StandardCharsets;

import org.apache.commons.lang3.StringUtils;
// kj bank import 2025-09-23 jwhong
//import org.kjbank.simple.core.crypto.seed.SeedUtil;
import com.eactive.eai.common.seed.SeedKJ;


public class SeedKJDecrypt extends PostfixMathCommand {
    public SeedKJDecrypt() {
        numberOfParameters = 2;
    }

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

        //샘플
        String seedSalt = ElinkTransactionContext.getSeedSalt();
        System.out.println("seedSalt = " + seedSalt);

        // USER FUNCTION에서 Parameter 에서 가져옴
        Object param2 = inStack.pop();
        String param2Str = String.valueOf(param2); // null 안전 처리      
        String decryptKey = StringUtils.leftPad(param2Str, 16, '0');     

        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;
        } else {
            throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
        }

        try {
        	String decryptedData = SeedKJ.decrypt(new String(value, StandardCharsets.UTF_8), decryptKey);
        	
        	inStack.push(decryptedData);
        } catch (Exception e) {
            //throw new ExecutionException(e.getMessage(), parameters, e);
            throw new ParseException(e.getMessage(), e);
        }    	
    }
}

