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 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.server.EAIServerManager;
import com.eactive.eai.common.util.Logger;


public class KFTCFaceFilter 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 = "kftcface";
	public static final String H_CLIENT_ID = "Client-Id";
	public static final String B_ORG_CODE = "org_code";
	public static final String B_TRANSACTION_ID = "transaction_id";
	public static final String B_REQUEST_DATETIME = "request_datetime";
	public static String instId = null;

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

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

		logger.debug("KFTCFaceFilter] PreFilter Processing Start!!");
		JSONObject returnMessage = null;
		String clientId = "";
		String orgCode = "034"; // 광주은행 행코드

		PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
		if (propGroupVo != null) {
			if (StringUtils.isEmpty(clientId))
				clientId = propGroupVo.getProperty(PROP_PREFIX + "." + H_CLIENT_ID);
			orgCode = propGroupVo.getProperty(PROP_PREFIX + "." + B_ORG_CODE);
		}

		String request_datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String reqDate = new SimpleDateFormat("yyMMdd").format(new Date());
		String reqTime = new SimpleDateFormat("HHmmss").format(new Date());
		// 기관코드(3) + 요청일자(6) -- 금결원 표준화 항목, 고정 9자리.
		// 요청시간(6) + 인스턴스ID(2) + RandomString(3) -- 기관별 생성 거래고유번호(11자리)
		// 기관코드(3) + 요청일자(6) + 요청시간(6) + 인스턴스ID(2) + RandomString(3) -- 20자리.
		String transaction_id = orgCode + reqDate + reqTime + instId + RandomStringUtils.random(3, 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_CLIENT_ID)) {
					filterHeaders.put(H_CLIENT_ID, inboundHeaderMap.get(H_CLIENT_ID));
					logger.debug("KFTCFaceFilter] Processing Key ["+H_CLIENT_ID+"], value ["+inboundHeaderMap.get(H_CLIENT_ID)+"]");
				} else {
					filterHeaders.put(H_CLIENT_ID, clientId);
					logger.debug("KFTCFaceFilter] Processing Key ["+H_CLIENT_ID+"], value ["+clientId+"]");
				}
			} else {
				filterHeaders.setProperty(H_CLIENT_ID, clientId);
				logger.debug("KFTCFaceFilter] Processing Key ["+H_CLIENT_ID+"], value ["+clientId+"]");
			}

		} 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_ORG_CODE, orgCode);
		returnMessage.put(B_TRANSACTION_ID, transaction_id);
		returnMessage.put(B_REQUEST_DATETIME, request_datetime);

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

}

