package com.hotent.base.util;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 消息Util工具类,在线程变量中添加消 ObjectFactory
 *
 * @company 广州宏天软件股份有限公司
 * @author yijj
 * @email yijj@jee-soft.cn
 * @date 2022年5月19日
 */
@Service
public class ThreadMethodUtil implements ContextThread{

	private static ThreadLocal<Map<String, List<ObjectFactory<?>>>> localMapFactory = new ThreadLocal<Map<String,List<ObjectFactory<?>>>>();

	//流程消息的key 异步请求
	public static final String POST_ASYNC = "post_async";

	/**
	 * 添加线程factoryList
	 * @param key
	 * @param factoryList
	 */
	public static void addMapFactory(String key,List<ObjectFactory<?>> factoryList){
		Map<String, List<ObjectFactory<?>>> map = localMapFactory.get();
		if(BeanUtils.isEmpty(map)){
			map = new HashMap<>();
		}
		map.put(key, factoryList);
		localMapFactory.set(map);
	}

	public static List<ObjectFactory<?>> getMapFactory(String key){
		Map<String, List<ObjectFactory<?>>> map = localMapFactory.get();
		if(BeanUtils.isEmpty(map)){
			return null;
		}
		if(map.containsKey(key)){
			return map.get(key);
		}
		return null;
	}

	public static List<ObjectFactory<?>> getMapFactory(String key,boolean clean){
		Map<String, List<ObjectFactory<?>>> map = localMapFactory.get();
		if(BeanUtils.isEmpty(map)){
			return null;
		}
		if(map.containsKey(key)){
			List<ObjectFactory<?>> factoryList = map.get(key);
			if(clean) {
				map.remove(key);
			}
			return factoryList;
		}
		return null;
	}

	public static void cleanMapFactory(){
		localMapFactory.remove();
	}


	public static void deleteMapFactory(String key) {
		Map<String, List<ObjectFactory<?>>> map = localMapFactory.get();
		map.remove(key);
	}

	@Override
	public void cleanAll() {
		cleanMapFactory();
	}
}
