package com.eactive.eai.custom.kjb.adapter.http.client.impl;

import java.util.Properties;
//import java.util.concurrent.Callable;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Node;
import org.json.simple.JSONObject;

import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
import com.eactive.eai.custom.kjb.adapter.http.client.filter.HttpClient5AdapterFilterFactory;
//import com.eactive.eai.custom.kjb.adapter.http.client.filter.HttpClientAdapterExceptionFilter;
import com.eactive.eai.custom.kjb.adapter.http.client.filter.HttpClientAdapterFilter;
//import com.eactive.eai.custom.kjb.adapter.http.client.filter.IBKOutCommonFilter;
//import com.eactive.eai.custom.kjb.adapter.http.client.filter.IBKOutExceptionFilter;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.node.ObjectNode;
//import com.ibk.eai.common.circuitbreaker.url.UrlCircuitBreakerManager;

//import io.github.resilience4j.circuitbreaker.CircuitBreaker;

/**
 * 1. 기능 : HttpClient5AdapterServiceRest 호출 전후 Filter 적용할 수 있는 기능을 제공한다.<br>
 * 2. 처리 개요 : <br>
 * 3. 주의사항 <br>
 *
 * @author :
 * @version : v 1.0.0
 * @see : HttpClientAdapterServiceFactory.java,
 *      HttpClientAdapterServiceSupport.java, HttpClient5AdapterServiceRest.java
 * @since :
 * 
 */
public class HttpClient5AdapterServiceRestAddFilter extends HttpClient5AdapterServiceRest
		implements HttpClientAdapterServiceKey {

	// 요청전 수행할 필터(쉼표(,)로 구분)
	static final String PRE_FILTERS = "PRE_FILTERS";

	// 요청후 수행할 필터(쉼표(,)로 구분)
	static final String POST_FILTERS = "POST_FILTERS";

//	// Adapter에서 Exception이 발생한 경우, 처리할 필터
//	static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";

	/**
	 * 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
	 * 3. 주의사항 <br>
	 *
	 * @param prop Http Adapter 속성 정보
	 * @return 반환 된 Object
	 * @exception Exception 수동 시스템 간 통신 중 발생
	 */
	public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {

		String adptGrpName = tempProp.getProperty(ADAPTER_GROUP_NAME);
		String adptName = tempProp.getProperty(ADAPTER_NAME);

		data = doPreFilters(adptGrpName, adptName, prop, data, tempProp);

		Object adapterResponse = super.execute(prop, data, tempProp);
		
//		//원본 url를 찾아서 있으면, 그것을 사용한다.
//		String url = tempProp.getProperty("URL_ORG");
//		if(StringUtils.isEmpty(url))
//			url = tempProp.getProperty(HttpClientAdapterServiceKey.URL);
//		
//		UrlCircuitBreakerManager cManager = UrlCircuitBreakerManager.getInstance();
//		CircuitBreaker circuitBreaker = cManager.getCircuitBreaker(url);
//		try {
//			if (circuitBreaker != null) {
//				if (logger.isDebugEnabled()) {
//					// ObjectMapper 인스턴스 생성
//					ObjectMapper objectMapper = new ObjectMapper();
//					// 서킷 브레이커의 메트릭 정보와 상태 정보를 직접 Node로 변환
//					ObjectNode combinedNode = objectMapper.createObjectNode();
//					combinedNode.put("state", circuitBreaker.getState().toString());
//					combinedNode.set("metrics", objectMapper.valueToTree(circuitBreaker.getMetrics()));
//					logger.debug("CircuitBreaker state [" + circuitBreaker.getName() + "] - " + combinedNode.toString());
//				}
//				adapterResponse = circuitBreaker.executeCallable(new HttpClientAdapterCallable(prop, data, tempProp, this));
//			} else {
//				adapterResponse = super.execute(prop, data, tempProp);
//			}
//		} catch (Exception e) {
//			adapterResponse = doExceptionFilters(adptGrpName, adptName, prop, adapterResponse, tempProp, e);
//			
//			if (adapterResponse instanceof JSONObject)
//				adapterResponse = ((JSONObject) adapterResponse).toJSONString();
//
//			if (adapterResponse instanceof Node)
//				adapterResponse = ((Node) adapterResponse).asXML();
//
//			return adapterResponse;
//		}

		adapterResponse = doPostFilters(adptGrpName, adptName, prop, adapterResponse, tempProp);
		if (adapterResponse instanceof JSONObject)
			adapterResponse = ((JSONObject) adapterResponse).toJSONString();

		if (adapterResponse instanceof Node)
			adapterResponse = ((Node) adapterResponse).asXML();

		return adapterResponse;
	}

//	protected Object callSuper(Properties prop, Object data, Properties tempProp) throws Exception {
//		return super.execute(prop, data, tempProp);
//	}

//	private class HttpClientAdapterCallable implements Callable<Object> {
//		Properties prop;
//		Object data;
//		Properties tempProp;
//		HttpClient5AdapterServiceRestAddFilter clientService;
//
//		public HttpClientAdapterCallable(Properties prop, Object data, Properties tempProp,
//				HttpClient5AdapterServiceRestAddFilter clientService) {
//			this.prop = prop;
//			this.data = data;
//			this.tempProp = tempProp;
//			this.clientService = clientService;
//		}
//
//		@Override
//		public Object call() throws Exception {
//			return clientService.callSuper(prop, data, tempProp);
//		}
//
//	}

	protected Object doPreFilters(String adptGrpName, String adptName, Properties prop, Object message,
			Properties tempProp) throws Exception {

//		boolean isSetCommonFilterInAdapterProp = false;
		// 1. adapter에 설정된 필터 수행
		String preFiltersStr = prop.getProperty(PRE_FILTERS);
		if (StringUtils.isNotEmpty(preFiltersStr)) {
			String[] preFilters = StringUtils.split(preFiltersStr, ",");
			for (String filterName : preFilters) {
				if (StringUtils.isBlank(filterName)) {
					continue;
				}

				logger.debug("HttpClient5AdapterServiceRestAddFilter] Processing Start [" + filterName + "]");
				HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());

				if (adapterFilter != null) {
//					if (adapterFilter instanceof IBKOutCommonFilter)
//						isSetCommonFilterInAdapterProp = true;

					message = adapterFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
				} else {
					throw new Exception("Failed get Filter Class: " + filterName);
				}
			}
		}

//		// 2. IBKOutCommonFilter 필터 수행(adapter 필터에서 수행하지 않을 때만)
//		if (!isSetCommonFilterInAdapterProp) {
//			HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
//					.createFilter(IBKOutCommonFilter.class.getName());
//			if (ibkFilter != null) {
//				message = ibkFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
//			}
//		} else {
//			logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'POST_FILTERS'. already in adapter filters");
//		}

		return message;
	}

	protected Object doPostFilters(String adptGrpName, String adptName, Properties prop, Object message,
			Properties tempProp) throws Exception {

//		boolean isSetCommonFilterInAdapterProp = false;
		// 1. adapter에 설정된 필터 수행
		String postFiltersStr = prop.getProperty(POST_FILTERS);
		if (StringUtils.isNotEmpty(postFiltersStr)) {
			String[] postFilters = StringUtils.split(postFiltersStr, ",");
			for (String filterName : postFilters) {
				if (StringUtils.isBlank(filterName)) {
					continue;
				}

				HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
				if (adapterFilter != null) {
//					if (adapterFilter instanceof IBKOutCommonFilter)
//						isSetCommonFilterInAdapterProp = true;
					message = adapterFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
				} else {
					throw new Exception("Failed get Filter Class: " + filterName);
				}
			}
		}

//		// 2. IBKOutCommonFilter 필터 수행
//		if (!isSetCommonFilterInAdapterProp) {
//			HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
//					.createFilter(IBKOutCommonFilter.class.getName());
//			if (ibkFilter != null) {
//				message = ibkFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
//			}
//		} else {
//			logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'PRE_FILTERS'. already in adapter filters");
//		}
		return message;
	}
	
//	protected Object doExceptionFilters(String adptGrpName, String adptName, Properties prop, Object message,
//			Properties tempProp, Exception e) throws Exception {
//		String exceptionFilterName = prop.getProperty(EXCEPTION_FILTER);
//		if (StringUtils.isEmpty(exceptionFilterName))
//			exceptionFilterName = IBKOutExceptionFilter.class.getSimpleName();
//			
//		HttpClientAdapterExceptionFilter exceptionFilter = HttpClient5AdapterFilterFactory.createExceptionFilter(exceptionFilterName.trim());
//		return exceptionFilter.doExceptionFilter(adptGrpName, adptName, prop, message, tempProp, e);
//		
//	}

}