/**
 * 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;

import com.crunii.micro.common.log.BusiLogComHttp;
import com.crunii.micro.common.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.context.ApplicationContext;
import org.springframework.core.NamedThreadLocal;
import org.springframework.util.ObjectUtils;

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

/**
 * @author 田平 create 2020年1月10日下午3:18:23
 */
@Slf4j
public class HttpClientHolder {

	public static final String REQ_BODY_KEY = HttpClientHolder.class + ".request.body.key";
	public static final String RSP_BODY_KEY = HttpClientHolder.class + ".response.body.key";

	public static ThreadLocal<Map<String, Object>> busiLogInfo = new NamedThreadLocal<Map<String, Object>>("HttpClientBusiLogInfo") {
		@Override
		protected Map<String, Object> initialValue() {
			return new HashMap<>(8);
		}
	};

	public static Map<String, Object> getBusiInfoAndClean() {
		busiLogInfo.get().clear();
		return busiLogInfo.get();
	}

	public static List<String> getHeaderInfo(Header[] headers) {
		if (!ObjectUtils.isEmpty(headers)) {
			List<String> list = new ArrayList<>(headers.length);
			for (int i = 0; i < headers.length; i++) {
				list.add(headers[i].toString());
			}
			return list;
		} else {
			return null;
		}
	}

	public static void doHttpLog() {
		try {
			ApplicationContext ctx = SpringUtil.getAppCtx();
			if (ctx != null) {
				BusiLogComHttp httpLog = ctx.getBean(BusiLogComHttp.class);
				if (httpLog != null) {
					httpLog.busiLogByMap(busiLogInfo.get());
					busiLogInfo.get().clear();
				} else {
					log.info("httpLog:{}", busiLogInfo.get());
				}
			} else {
				log.info("httpLog:{}", busiLogInfo.get());
			}
		} finally {
			busiLogInfo.get().clear();
		}

	}

}
