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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.commons.lang3.RandomStringUtils;

import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.property.PropGroupVO;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.Logger;


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

	public static final String KJB_HEADER = "KJB_Header";
	public static final String PROP_PREFIX = "kftcp2p";
	public static final String H_ORG_CODE = "org_code";
	public static final String H_TRX_NO = "api_trx_no";
	public static final String H_TRX_DTM = "api_trx_dtm";
	public static String instId = null;

	static {
		EAIServerManager eaiServerManager = EAIServerManager.getInstance();
		instId = eaiServerManager.getInstId();
	}

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

		logger.debug("KFTCP2PFilter] PreFilter Processing Start!!");
		String orgCode = "D210400012"; // 광주은행 개발 기관코드(운영: K210800020)

		PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
		if (propGroupVo != null) {
			orgCode = propGroupVo.getProperty(PROP_PREFIX + "." + H_ORG_CODE);
		}
	
		String apiTrxDtm = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
		String apiTrxTm = new SimpleDateFormat("HHmmss").format(new Date());
		// 기관코드(10) + 인스턴스ID(2) + 일시(6) + RandomString(2) -- 총 20자리 
		String apiTrxNo = orgCode + instId + apiTrxTm + RandomStringUtils.random(2, true, true).toUpperCase(); 

		Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
		if (filterHeaders == null) {
			filterHeaders = new Properties();
			tempProp.put("FILTERHEADER", filterHeaders);
		}
		try {
			Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);

			if (!inboundHeaderMap.isEmpty()) {
				if (inboundHeaderMap.containsKey(H_TRX_NO)) {
					filterHeaders.put(H_TRX_NO, inboundHeaderMap.get(H_TRX_NO));
					logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_NO+"], value ["+inboundHeaderMap.get(H_TRX_NO)+"]");
				} else {
					filterHeaders.put(H_TRX_NO, apiTrxNo);
					logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_NO+"], value ["+apiTrxNo+"]");
				}
				if (inboundHeaderMap.containsKey(H_TRX_DTM)) {
					filterHeaders.put(H_TRX_DTM, inboundHeaderMap.get(H_TRX_DTM));
					logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_DTM+"], value ["+inboundHeaderMap.get(H_TRX_DTM)+"]");
				} else {
					filterHeaders.put(H_TRX_DTM, apiTrxDtm);
					logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_DTM+"], value ["+apiTrxDtm+"]");
				}
			} else {
				filterHeaders.put(H_TRX_NO, apiTrxNo);
				filterHeaders.put(H_TRX_DTM, apiTrxDtm);
			}
			logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_NO+"], value ["+filterHeaders.getProperty(H_TRX_NO)+"]");
			logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_DTM+"], value ["+filterHeaders.getProperty(H_TRX_DTM)+"]");

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

}

