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

import java.util.Arrays;
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.common.TransactionContextKeys;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;


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

	public static final String X_TRACE_ID = "partnerTraceId";
	public static final String TRACE_ID = "traceId";
	
	public static final String PROPERTIES_GROUP_NAME = "HttpHeaderFilter";
	public static final String HEADER_KEY_NAMES = "AsyncReponseFilter";
	

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

		logger.debug("AsyncReponseFilter] PreFilter Processing Start!!");
		String traceId = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");

		Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
		if (filterHeaders == null) {
			filterHeaders = new Properties();
			tempProp.put("FILTERHEADER", filterHeaders);
		}
		
		String propValue = PropManager.getInstance().getProperty(PROPERTIES_GROUP_NAME, HEADER_KEY_NAMES, "").trim();

		String[] headerKeyNames = propValue.split(",");
		
		
		headerKeyNames = Arrays.stream(headerKeyNames)
		        .map(String::trim)
		        .toArray(String[]::new);
		
		try {
			Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);

			if (!inboundHeaderMap.isEmpty()) {
				if (inboundHeaderMap.containsKey(X_TRACE_ID)) {
					filterHeaders.put(X_TRACE_ID, inboundHeaderMap.get(X_TRACE_ID));
					logger.debug("AsyncReponseFilter] Processing Key ["+X_TRACE_ID+"], value ["+inboundHeaderMap.get(X_TRACE_ID)+"]");
				}
				
				if (inboundHeaderMap.containsKey(TransactionContextKeys.X_LOAN_TOKEN)) {
					filterHeaders.put(TransactionContextKeys.X_LOAN_TOKEN, inboundHeaderMap.get(TransactionContextKeys.X_LOAN_TOKEN));
					logger.debug("AsyncReponseFilter] Processing Key ["+TransactionContextKeys.X_LOAN_TOKEN+"], value ["+inboundHeaderMap.get(TransactionContextKeys.X_LOAN_TOKEN)+"]");
				}
			}
			
			filterHeaders.setProperty(TRACE_ID, traceId);
			logger.debug("AsyncReponseFilter] Processing Key ["+TRACE_ID+"], value ["+traceId+"]");
			
			for (String keyName : inboundHeaderMap.keySet()) {

				if (StringUtils.equalsAnyIgnoreCase(keyName, headerKeyNames)) {
					String value = inboundHeaderMap.get(keyName);
					filterHeaders.put(keyName, value);
					logger.debug("AsyncReponseFilter] Processing Key [" + keyName + "], value [" + value + "]");
				}

			}

		} 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;
	}

}

