package com.persagy.adm.server.custom.util;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.digital.entity.ObjectDigital;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Iterator;

public class DataExtrasUtil {

	private static HashSet<String> admObjFields = getEntityFields(ObjectDigital.class, "buildingId", "floorId", "bimId", "containerId");

	private static String objExtraCol = "infos";

	private static HashSet<String> getEntityFields(Class<?> cls, String... extFields){
		HashSet<String> set = new HashSet<>();
		Field[] fields = ReflectUtil.getFields(cls);
		for(Field field : fields) {
			if(Modifier.isStatic(field.getModifiers()))
				continue;
			TableField tableField = (TableField)field.getAnnotation(TableField.class);
			if(tableField == null || tableField.exist())
				set.add(field.getName());
		}
		for(String f : extFields) {
			set.add(f);
		}
		return set;
	}

	public static void packObjExtras(ObjectNode objNode){
		ObjectNode extraNode = objNode.putObject(objExtraCol);
		Iterator<String> iter = objNode.fieldNames();

		while(iter.hasNext()) {
			String fieldName = iter.next();
			if(admObjFields.contains(fieldName))
				continue;
			else {
				extraNode.set(fieldName, objNode.get(fieldName));
				iter.remove();
			}
		}
	}

	public static void unpackObjExtras(ObjectNode objNode){
		JsonNode extraNode = objNode.remove(objExtraCol);
		if(extraNode instanceof ObjectNode) {
			ObjectNode infos = (ObjectNode) extraNode;

			Iterator<String> iter = infos.fieldNames();
			while(iter.hasNext()) {
				String fieldName = iter.next();
				objNode.set(fieldName, infos.get(fieldName));
			}
		}
	}

}
