package com.artfess.bpm.api.context;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.artfess.base.model.HtJsonNodeFactory;
import com.artfess.base.util.BeanUtils;
import com.artfess.bpm.api.cmd.ActionCmd;
import com.artfess.bpm.api.cmd.BaseActionCmd;
import com.artfess.bpm.api.constant.BpmConstants;
import com.artfess.bpm.util.BoDataUtil;

/**
 * 流程上下文数据工具类。
 * @author ray
 *
 */
public class BpmContextUtil {
	/**
	 * 获取上下文的bo实例数据。
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,ObjectNode> getBoFromContext(){
		ActionCmd cmd = ContextThreadUtil.getActionCmd();
		Map<String, ObjectNode> map =new HashMap<>();
		if (cmd == null || cmd.getTransitVars(BpmConstants.BO_INST) == null) {
			return map;
		}
		
		Map<String, ObjectNode> boDatas =(Map<String, ObjectNode>) cmd.getTransitVars(BpmConstants.BO_INST);
		for (Iterator<Entry<String, ObjectNode>> iterator = boDatas.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, ObjectNode> next = iterator.next();
			ObjectNode obj= next.getValue();
			if (obj.hasNonNull("data") && (obj.get("data") instanceof ObjectNode)) {
				obj = (ObjectNode) obj.get("data");
			}
			map.put(next.getKey(),HtJsonNodeFactory.build().htObjectNode(obj));
		}
		return map;
	}
	
	/**
	 * 将bo数据放到上下文。
	 * 这种试用在没有cmd的环境中。
	 * @param ObjectNodes
	 * @throws IOException 
	 */
	public static void setBoToContext(List<ObjectNode> boDatas) throws Exception{
		ActionCmd cmd =ContextThreadUtil.getActionCmd();
		if (BeanUtils.isEmpty(cmd)) {
			cmd =new BaseActionCmd();
			ContextThreadUtil.setActionCmd(cmd);
		}
		cmd.addTransitVars(BpmConstants.BO_INST, BoDataUtil.converBodataListToMap(boDatas));
	}
	
}
