package com.eactive.eai.adapter.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.logger.HttpAdapterExtraHeaderVo;
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
import com.eactive.eai.common.util.Logger;

public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
	
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private static boolean httpHeaderLogMode = HttpAdapterExtraLogUtil.isHttpHeaderMode();
	
	@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    	
    	logger.debug("httpHeader logging Interceptor start");
    	
    	if (!httpHeaderLogMode) {
    		logger.info("httpHeader logging off - use.http.header.log");
    		return;
    	}
    	
        Properties transactionProp = (Properties) request.getAttribute(TransactionContextKeys.TRANSACTION_PROP);
        if(transactionProp == null || "ASYN".equals(transactionProp.getProperty(HttpAdapterServiceKey.INBOUND_SYNC_ASYNC_TYPE))){
        	logger.debug("httpHeader logging Interceptor ASYNC");
            return;
        }

        String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
        String adapterGroupName = transactionProp.getProperty(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME);
        String adapterName = transactionProp.getProperty(HttpClientAdapterServiceKey.ADAPTER_NAME);
        String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
        String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
        
        logger.debug(String.format( "httpHeader logging Interceptor uuid=%s, adapterGroupName=%s, adapterName=%s, url=%s, method=%s", uuid, adapterGroupName, adapterName, url, method));

        if(StringUtils.isBlank(uuid) || StringUtils.isBlank(adapterGroupName)){
            return;
        }

        Map<Object, Object> headerMap = new HashMap<>();
        // 응답 헤더 로깅
        for (String headerName : response.getHeaderNames()) {
            String headerValue = response.getHeader(headerName);
            logger.debug(String.format( "httpHeader logging Interceptor headerKey=%s, headerValue=%s", headerName, headerValue));
            headerMap.put(headerName, headerValue);
        }
        
        String body = transactionProp.getProperty(HttpAdapterExtraLogUtil.BODY_FIELD_NAME);
		if (StringUtils.isNotEmpty(body)) {
			headerMap.put(HttpAdapterExtraLogUtil.BODY_FIELD_NAME, body);
		}

        int httpStatusCode = response.getStatus();
        HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, headerMap, url, method, httpStatusCode);
    }

}