package com.liangjian.dataplatform.member.entity.vo.tagrules;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;

import java.io.IOException;
import java.util.List;

/**
 * @Author: 黄子奇
 * @Date: 2019/9/10 14:02
 *
 * 由于接口提交上来的json是不知道类型的，所有写一个反序列化器来生成指定的类型
 */
public class LogicNodeDeserializer extends JsonDeserializer<LogicNode> {

    @Override
    public LogicNode deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode node = parser.getCodec().readTree(parser);
        JsonNode extNodes = node.get("extNodes");
        if(extNodes == null || extNodes.isNull()) {
            //没有这个节点，说明是不含层级的那个
            String type = node.get("logicType").asText();
            LogicType logicType = LogicType.valueOf(type);
            JsonNode binNode = node.get("binOperation");
            BinOperation binOperation = objectMapper.treeToValue(binNode, BinOperation.class);
            return new SimpleLogicNode(logicType,binOperation);
        } else {
            //有这个节点，说明是有层级关系的那个
            String type = node.get("logicType").asText();
            LogicType logicType = LogicType.valueOf(type);
            JsonNode binNode = node.get("binOperation");
            BinOperation binOperation = objectMapper.treeToValue(binNode, BinOperation.class);

            ObjectReader objectReader = objectMapper.readerFor(new TypeReference<List<LogicNode>>() {});
            List<LogicNode> exts = objectReader.readValue(extNodes);
            return new BracketsLogicNode(logicType,binOperation,exts);
        }
    }
}
