package com.persagy.adm.diagram.core.build;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.adm.diagram.core.DataStrategy;
import com.persagy.adm.diagram.core.model.Diagram;
import com.persagy.adm.diagram.core.model.legend.Legend;

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

/**
 * 图例加载
 * @author zhaoyk
 */
public class LegendLoader {

	private Diagram diagram;

	private DataStrategy dataStrategy;

	private CalcContext context;

	private HashMap<String, List<Legend>> legendsCache = new HashMap<>();

	public LegendLoader(Diagram diagram, DataStrategy dataStrategy) {
		this.diagram = diagram;
		this.dataStrategy = dataStrategy;
	}

	public void setContext(CalcContext context) {
		this.context = context;
	}

	public Legend findLegend(String classCode, ObjectNode obj){
		List<Legend> legends = legendsCache.get(classCode);
		if (legends == null) {
			legends = dataStrategy.getLegendsForEquipment(classCode);
			if (legends == null) {
				legends = new ArrayList<>();
			}
			legendsCache.put(classCode, legends);
		}
		if(legends.size() > 0) {
			Legend l0 = null, l1 = null;
			for(Legend legend : legends) {
				//系统图类型匹配
				boolean typeMatch = CollUtil.isNotEmpty(legend.getDiagramTypes()) && legend.getDiagramTypes().contains(diagram.getType());
				//过滤条件匹配
				boolean filterMatch;
				if(obj != null && legend.getDataFilter() != null) {
					filterMatch = legend.getDataFilter().filter(obj, context);
				} else {
					filterMatch = true;
				}

				if(typeMatch && filterMatch) {
					return legend;
				}

				if(typeMatch && l0 == null) {
					l0 = legend;
				}
				if(filterMatch && l1 == null) {
					l1 = legend;
				}
			}
			if(l0 != null) {
				return l0;
			}
			if(l1 != null) {
				return l1;
			}
			//没有优先匹配的话取第一个
			return legends.get(0);
		}

		//返回一个缺省图例
		return emptyLegend();
	}

	public Legend findLegendById(String legendId, String systemCode) {
		Legend legend = null;
		if(legendId != null) {
			legend = dataStrategy.getLegend(legendId, systemCode); //TODO 批量查询优化
		}
		return legend != null ? legend : emptyLegend();
	}

	public static Legend emptyLegend(){
		Legend l = new Legend();
		l.setWidth(100);
		l.setHeight(100);
		return l;
	}

}
