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

import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.util.Logger;

public class SimpleFrameworkFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
	protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

	public static final String CLIENTID = "clientId";
	public static final String TRACEID = "traceId";
	public static final String GUID = "guid";
	public static final String RECEIVEDTIMESTAMP = "receivedTimestamp";
	public static final String PARTNER_TRACE_ID = "partnerTraceId";

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

		logger.debug("SimpleFrameworkFilter] PreFilter Processing Start!!");

		Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
		if (filterHeaders == null) {
			filterHeaders = new Properties();
			tempProp.put("FILTERHEADER", filterHeaders);
		}
		
		Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);	
		
		try {
    		/* 업체정보 */
			String clientId = tempProp.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
			if (StringUtils.isEmpty(clientId)) clientId = "";
			filterHeaders.put(CLIENTID, clientId);
			logger.debug("SimpleFrameworkFilter] Processing Key ["+CLIENTID+"], value ["+clientId+"]");
            
            /* APIM 거래추적자 */
            String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");
			filterHeaders.put(TRACEID, uuid);
			logger.debug("SimpleFrameworkFilter] Processing Key ["+TRACEID+"], value ["+uuid+"]");
            
            /* GUID */
            String guid = tempProp.getProperty(TransactionContextKeys.GUID, "");
            filterHeaders.put(GUID, guid);
			logger.debug("SimpleFrameworkFilter] Processing Key ["+GUID+"], value ["+guid+"]");
               
            /* 최초요청시간  */
            String receivedTimestamp = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REQUESTED_TIME, "");
            filterHeaders.put(RECEIVEDTIMESTAMP, receivedTimestamp);
			logger.debug("SimpleFrameworkFilter] Processing Key ["+RECEIVEDTIMESTAMP+"], value ["+receivedTimestamp+"]");
			
			String partnerTraceId = inboundHeaderMap.getOrDefault(PARTNER_TRACE_ID, "");
			filterHeaders.put(PARTNER_TRACE_ID, partnerTraceId);
			logger.debug("SimpleFrameworkFilter] Processing Key ["+PARTNER_TRACE_ID+"], value ["+partnerTraceId+"]");
			
			String x_loan_token = inboundHeaderMap.getOrDefault(TransactionContextKeys.X_LOAN_TOKEN, "");
			filterHeaders.put(TransactionContextKeys.X_LOAN_TOKEN, x_loan_token);
			logger.debug("SimpleFrameworkFilter] Processing Key ["+TransactionContextKeys.X_LOAN_TOKEN+"], value ["+x_loan_token+"]");

			
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		return message;
	}
	
	public Map<String, String> getInboundHeaderProp(Properties prop) {
		Properties header = new Properties();
		Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
		try {
			Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
			if (headerObj instanceof Properties) {    //tomcat
				header = (Properties) headerObj;
				for (String name : header.stringPropertyNames()) {
					inboundHeaderMap.put(name, header.getProperty(name));
				}
			} else if (headerObj instanceof String) {  //weblogic
				String str = (String) headerObj;
				str = str.substring(1, str.length() - 1);
				// key=value 쌍 분리
				String[] entries = str.split(",");
				for (String entry : entries) {
				    String[] kv = entry.split("=", 2);
				    if (kv.length == 2) {
				    	inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
				    }
				}
			}	
		} catch (Exception  e) {
		    e.printStackTrace();
		}
		return inboundHeaderMap;
	}

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

}
