package com.eactive.eai.custom.adapter.http.client.impl.filter;

import java.util.Properties;

import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
import com.eactive.eai.common.util.JacksonUtil;
import com.eactive.eai.util.JsonPathUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * 토스 암복호화에 맟추어 커스텀
 */
public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {

	private final OutCryptoFilter filter = new OutCryptoFilter();

	protected Properties setProp(Properties tempProp) {
		tempProp.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
		tempProp.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
		return tempProp;
	}
	

	@Override
	public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
			throws Exception {
		String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
		
		JsonNode root = JacksonUtil.readTree(message);
		ObjectNode rootObjectNode = (ObjectNode) root;
		JsonNode header = rootObjectNode.get(headerGroupName);
		rootObjectNode.remove(headerGroupName);
		
		String xEmpNm = header.get("x-emp-nm").asText();
		tempProp.setProperty("x-emp-nm", xEmpNm);
		tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, xEmpNm);
		String xChnlNm = header.get("x-chnl-nm").asText();
		tempProp.setProperty("x-chnl-nm", xChnlNm);
		
		Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
		
		ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
		encJson.set(headerGroupName, header);
		
		return encJson;
	}

	@Override
	public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
			Properties tempProp) throws Exception {
		return filter.doPostFilter(adptGrpName, adptName, setProp(prop), message, setProp(tempProp));
	}
	
}
