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

import java.util.Map.Entry;
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.StringUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
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.util.Logger;


public class NICECreditFilter 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 = "nicecredit";
	public static final String H_PRODUCTID = "ProductID";
	public static final String B_REQ_DTM = "req_dtm";
	public static final String B_GOODS_CLS = "goods_cls";

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

		JSONObject returnMessage = null;
		String productId = "2303102120";
		String reqDtm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String goodsCls = "KJBAPI0001";

		PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
		if (propGroupVo != null) {
			productId = propGroupVo.getProperty(PROP_PREFIX + "." + H_PRODUCTID);
			goodsCls = propGroupVo.getProperty(PROP_PREFIX + "." + B_GOODS_CLS);
		}

		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 != null && inboundHeaderMap.containsKey(H_PRODUCTID)) {
				for (Entry<String, String> e : inboundHeaderMap.entrySet()) {
					String key = (String) e.getKey();
					String value = (String) e.getValue();
	
					if (StringUtils.equalsIgnoreCase(key, H_PRODUCTID)) {
						filterHeaders.setProperty(key, value);
					}
					if (logger.isDebugEnabled()) {
						logger.debug("Request Header :" + key + "=[" + value + "]");
					}
				}
			} else {
				filterHeaders.setProperty(H_PRODUCTID, productId);
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		AdapterManager adapterManager = AdapterManager.getInstance();
		AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adptGrpName);
		String encode = adptGrpVO.getMessageEncode();
		if (message == null) {
			returnMessage = new JSONObject();
		} else {
			if (message instanceof JSONObject) {
				returnMessage = (JSONObject) message;
			} else if (message instanceof String) {
				returnMessage = parseJson((String) message);
			} else if (message instanceof byte[]) {
				returnMessage = parseJson(new String((byte[]) message, encode));
			}
		}
		
		returnMessage.put(B_REQ_DTM, reqDtm);
		returnMessage.put(B_GOODS_CLS, goodsCls);

		return returnMessage.toJSONString();
	}

	private JSONObject parseJson(String message) throws Exception {
		if (message == null) {
			return null;
		}

		return (JSONObject) JSONValue.parse(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;
	}

}

