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

import java.util.Stack;

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

import java.nio.charset.StandardCharsets;

// security-1.0.0.jar 사용으로 변경 2026-01-05
import com.eactive.eai.security.seed.Seed;
//kj bank import 2025-09-23 jwhong
//import com.eactive.eai.common.seed.SeedKJ;

import org.apache.commons.lang3.StringUtils;
import java.util.Base64;
import com.eactive.eai.common.context.ElinkTransactionContext;

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

    public void run(Stack inStack) throws ParseException {
        checkStack(inStack);
           
        String seedKey = ElinkTransactionContext.getSeedKey();
        String encryptKey = StringUtils.leftPad(seedKey, 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 encryptedData = Seed.encrypt(encryptKey, new String(value, StandardCharsets.UTF_8));
        	
        	inStack.push(encryptedData);
        } catch (Exception e) {
            //throw new ExecutionException(e.getMessage(), parameters, e);
            throw new ParseException(e.getMessage(), e);
        }    	
    }
}