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

import cn.hutool.core.collection.CollUtil;
import com.persagy.adm.diagram.core.model.base.Container;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 模板检查修正
 * @author zhaoyk
 */
public class TemplateChecker {

	private DiagramTemplate template;

	public TemplateChecker(DiagramTemplate template) {
		this.template = template;
	}

	public void checkAndFix(){
		template.init();

		if(template.getMainPipes() != null){
			for(MainPipe mainPipe : template.getMainPipes()) {
				fixMainPipeRelCons(mainPipe);
			}
		}

		//TODO 动态组设置检查，关系过滤条件检查
	}

	private void fixMainPipeRelCons(MainPipe mainPipe){
		List<Container> relCons = mainPipe.getRelatedContainerList();
		if(CollUtil.isNotEmpty(relCons)){
			for (int i = 0; i < relCons.size(); i++) {
				Container c1 = relCons.get(i);
				for (int j = i + 1; j < relCons.size(); j++) {
					Container c2 = relCons.get(j);
					if(c1.isParentOf(c2)){
						relCons.remove(j);
						j--;
					} else if(c2.isParentOf(c1)){
						relCons.remove(i);
						i--;
						break;
					}
				}
			}
			mainPipe.setRelatedContainers(relCons.stream().map(con -> con.getId()).collect(Collectors.toList()));
		} else {
			mainPipe.setRelatedContainers(null);
		}
	}

}
