package com.blueland.bpm.engine.core.handler;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blueland.bpm.common.util.ApplicationContextHolder;
import com.blueland.bpm.common.util.ClassUtils;
import com.blueland.bpm.engine.config.model.GloblBizProcessHandler;
import com.blueland.bpm.engine.config.service.GloblBizProcessHandlerManager;
/**
 * 引擎业务应用全局回调处理工厂
 * @version:  1.0
 * @author lw 
 */
public class GlobalBizHandlerFactory {
	protected static Logger logger = LoggerFactory.getLogger(GlobalBizHandlerFactory.class);
	private static GlobalBizHandlerFactory globalProcessHandlerFactory=new GlobalBizHandlerFactory();
	static GloblBizProcessHandlerManager globlBizProcessHandlerManager=(GloblBizProcessHandlerManager) ApplicationContextHolder.getBean("globlBizProcessHandlerManager");
	private GlobalBizHandlerFactory(){
		
	}

	// WfBusinessAgent services
	protected static Map<String, List<GlobalBizHandler>> globalProcessHandlerServiceMap = null;

	static{
		globalProcessHandlerServiceMap = new HashMap<String, List<GlobalBizHandler>>();
	}
	protected static void initGloblBizProcessHandler(){
		List<GloblBizProcessHandler> globlBizProcessHandlers=globlBizProcessHandlerManager.findByExample(null);
		for(GloblBizProcessHandler globlBizProcessHandler:globlBizProcessHandlers){
			if("1".equals(globlBizProcessHandler.getGbphStatus())) {
				addGlobalProcessHandlerService(globlBizProcessHandler.getGbphType(),globlBizProcessHandler.getGbphClassName());
			}
		}
	}
	public static GlobalBizHandlerFactory getInstance(){
		if(globalProcessHandlerServiceMap.isEmpty()){
			initGloblBizProcessHandler();
		}
		return globalProcessHandlerFactory;
	}
	public  GlobalBizHandlerFactory getWfBusinessAgentFactory(){
		
		return globalProcessHandlerFactory;
	}
	
	public  Map<String, List<GlobalBizHandler>> getGlobalProcessHandlerServiceMap() {
		return globalProcessHandlerServiceMap;
	}
	
	public  List<GlobalBizHandler> getGlobalProcessHandlerService(String agentType) {
		return globalProcessHandlerServiceMap.get(agentType);
	}
	
	public static void addGlobalProcessHandlerService(String agentType,
			String wfBusinessAgentServiceClass) {
		if (StringUtils.isEmpty(agentType)) {
			return;
		}
		List<GlobalBizHandler> agentServices = globalProcessHandlerServiceMap
				.get(agentType);
		if (agentServices == null) {
			agentServices = new ArrayList<GlobalBizHandler>();
			globalProcessHandlerServiceMap.put(agentType, agentServices);
		}
		Object obj = null;
		try {
			obj =ClassUtils.getInstance(wfBusinessAgentServiceClass);
		} catch (Exception e) {
			logger.error("", e);
		}
		if (obj != null)
			agentServices.add((GlobalBizHandler) obj);

	}
}
