package com.persagy.adm.diagram.core.model.logic;

import cn.hutool.core.util.StrUtil;
import com.persagy.adm.diagram.core.DataStrategy;
import com.persagy.adm.diagram.core.model.Diagram;
import com.persagy.adm.diagram.core.model.DiagramNode;
import com.persagy.adm.diagram.core.model.EquipmentNode;
import com.persagy.adm.diagram.core.model.Line;
import com.persagy.adm.diagram.core.model.base.Container;
import com.persagy.adm.diagram.core.model.base.IDataBind;
import com.persagy.adm.diagram.core.model.template.DiagramTemplate;
import com.persagy.adm.diagram.core.model.template.MainPipe;

import java.util.HashMap;

/**
 * 系统图计算上下文
 * @author zhaoyk
 */
public class CalcContext {

	private Diagram diagram;

	private DiagramTemplate template;

	private DataStrategy dataStrategy;

	/**
	 * 当前动态组
	 */
	private Object currentGroup;

	/**
	 * 记录已经使用的数据id和对应的组件
	 */
	private HashMap<String, IDataBind> equipMap = new HashMap<>();

	/**
	 * 记录已经使用的关系id和对应的连线
	 */
	private HashMap<String, Line> lineMap = new HashMap<>();

	public CalcContext(Diagram diagram) {
		this.diagram = diagram;
		this.template = diagram.getTemplate();

		init();
	}

	private void init() {
		//记录节点中已使用的数据id
		diagram.getNodes().forEach(node -> {
			if (EquipmentNode.TYPE.equals(node.getCompType())) {
				equipMap.put(((EquipmentNode) node).getDataObjectId(), (EquipmentNode)node);
			}
		});
		//记录干管中已使用的数据id
		if(template != null && template.getMainPipes() != null) {
			template.getMainPipes().forEach(mainPipe -> {
				if(StrUtil.isNotBlank(mainPipe.getDataObjectId())) {
					equipMap.put(mainPipe.getDataObjectId(), mainPipe);
				}
			});
		}

		diagram.getLines().forEach(line -> {
			if (StrUtil.isNotBlank(line.getDataObjectId())){
				lineMap.put(line.getDataObjectId(), line);
			}
		});
	}

	public <T> T getComp(String id, String type) {
		//TODO 按动态组获取
		if(MainPipe.TYPE.equals(type)) {
			return (T)template.getMainPipeById(id);
		} else if(EquipmentNode.TYPE.equals(type)) {
			for(DiagramNode node : diagram.getNodes()) {
				if(node.getId().equals(id)){
					return (T)node;
				}
			}
		} else if(Container.TYPE.equals(type)) {
			return (T)template.getContainerById(id);
		} else {
			//TODO 其他类型
		}
		return null;
	}

	public DataStrategy getDataStrategy() {
		return dataStrategy;
	}

	public void setDataStrategy(DataStrategy dataStrategy) {
		this.dataStrategy = dataStrategy;
	}

	public Diagram getDiagram() {
		return diagram;
	}

	public DiagramTemplate getTemplate() {
		return template;
	}

	public HashMap<String, IDataBind> getEquipMap() {
		return equipMap;
	}

	public HashMap<String, Line> getLineMap() {
		return lineMap;
	}

	public String getProjectId() {
		return diagram.getProjectId();
	}

	public String getGroupCode() {
		return diagram.getGroupCode();
	}

}
