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

import java.util.Properties;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.util.Logger;
import com.nimbusds.jose.shaded.gson.JsonObject;

public class TraceBodyFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {

	protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
	
	public static final String BIZ_HEADER = "header";
	public static final String GUID = "guid";
	public static final String TRACEID = "traceId";

	@Override
	public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
			throws Exception {

		JSONObject bizJsonStr = null;

		if (message instanceof String) {

			bizJsonStr = (JSONObject) JSONValue.parse((String) message);
			
			if ( bizJsonStr == null ) return message; //json string이 아님.

			if (bizJsonStr.containsKey(BIZ_HEADER)) {
				JSONObject bizHeader = (JSONObject) bizJsonStr.get(BIZ_HEADER);

				putBizHeaderData(bizHeader, tempProp);

			}else {
				
				JSONObject bizHeader = new JSONObject();
				bizJsonStr.put(BIZ_HEADER, bizHeader);
				putBizHeaderData(bizHeader, tempProp);
				
			}

		}

		return bizJsonStr != null ? bizJsonStr.toJSONString() : message;
	}
	
	static private void putBizHeaderData(JSONObject bizHeader, Properties tempProp) {

		String traceId = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");

		String guid = tempProp.getProperty(TransactionContextKeys.GUID, "");

		bizHeader.put(GUID, guid);
		logger.debug("Processing Key [" + GUID + "], value [" + guid + "]");

		bizHeader.put(TRACEID, traceId);
		logger.debug("Processing Key [" + TRACEID + "], value [" + traceId + "]");
	}

	@Override
	public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
			Properties tempProp) throws Exception {
		// TODO Auto-generated method stub
		return message;
	}

}
