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

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.annotations.Expose;
import com.persagy.adm.diagram.core.DiagramBuilder;

import java.util.Objects;

/**
 * 匹配过滤器
 * @author zhaoyk
 */
public class MatchFilter extends DataFilter {

	public static final String EQUALS = "equals";

	public static final String CONTAINS = "contains";

	public static final String OBJ_NAME = "name";

	public static final String OBJ_INFOS = "infos.";

	public static final String VALUE_EMPTY = "value.empty";

	@Expose
	private String object;

	@Expose
	private String operation;

	@Expose
	private String value;

	public MatchFilter(){
		this.type = TYPE_MATCH;
	}

	@Override
	protected boolean judge(Object data) {
		Object param = null;
		if (data instanceof ObjectNode) {
			if(object.equals(MatchFilter.OBJ_NAME)) {
				param = DiagramBuilder.getName((ObjectNode)data);
			} else if(object.startsWith(MatchFilter.OBJ_INFOS)) {
				String infoCode = object.substring(MatchFilter.OBJ_INFOS.length());
				param = ((ObjectNode)data).get(infoCode);
			}
		}

		if (EQUALS.equals(operation)) {
			if(VALUE_EMPTY.equals(value)){
				return param == null || StrUtil.isBlank(param.toString());
			} else {
				Object val = value;
				if(param instanceof Number) {
					try {
						val = Double.parseDouble(value);
					}catch (Exception e) {

					}
				}
				return Objects.equals(param, val);
			}
		} else if(CONTAINS.equals(operation)) {
			//简单处理，暂时只考虑字符串，多个匹配项之间使用';'隔开
			String strData = data != null ? data.toString() : "";
			String[] arr = value.split(";");
			for(String s : arr) {
				if(!strData.contains(s))
					return false;
			}
			return true;
		}
		return false;
	}

	public String getObject() {
		return object;
	}

	public void setObject(String object) {
		this.object = object;
	}

	public String getOperation() {
		return operation;
	}

	public void setOperation(String operation) {
		this.operation = operation;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

}
