/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.http.interceptor;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.crunii.micro.common.constants.CommonConstants;
import com.crunii.micro.common.http.HttpClientHolder;
import com.crunii.micro.common.utils.BusiLogUtil;
import com.crunii.micro.common.utils.JsonUtil;

/**
 * @author 田平 create 2020年1月10日上午11:27:08
 *
 */
public class LogHttpRspInterceptor implements HttpResponseInterceptor {

	@Override
	public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
		HttpEntity entity = response.getEntity();
		ContentType ct = ContentType.get(entity);
		Charset cst = null;
		if (ct != null) {
			cst = ct.getCharset();
		} else {
			cst = Charsets.UTF_8;
		}
		Map<String, Object> recvData = new HashMap<String, Object>();
		Map<String, Object> busiInfo = HttpClientHolder.busiLogInfo.get();

		Date callTime = (Date) busiInfo.getOrDefault("callTime", new Date());
		long useTime = System.currentTimeMillis() - callTime.getTime();
		HttpClientHolder.busiLogInfo.get().put("useTime", useTime);
		String body = (String) busiInfo.remove(HttpClientHolder.RSP_BODY_KEY);
		if (ObjectUtils.isEmpty(body)) {
			if (entity != null) {
				String contentType = entity.getContentType() != null ? entity.getContentType().getValue() : null;
				if (BusiLogUtil.checkContentType(contentType)) {
					BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
					response.setEntity(bufferedHttpEntity);
					body = EntityUtils.toString(bufferedHttpEntity, cst);
					recvData.put("body", body);
				} else {
					recvData.put("body", "can not record body!");
				}
			}
		} else {
			recvData.put("body", body);
		}

		recvData.put("headers", HttpClientHolder.getHeaderInfo(response.getAllHeaders()));

		busiInfo.put("recvData", JsonUtil.getJsonString(recvData));
		busiInfo.put("callResult", CommonConstants.RESULT_SUCCESS);
		HttpClientHolder.doHttpLog();
	}

}
