package com.persagy.dmp.rwd.parser.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.rwd.parser.entity.ParserResult;

import java.io.IOException;
import java.util.Set;

/**
 * 布尔信息点 处理器
 * @author Charlie Yu
 * @date 2021-07-12
 */
public class BooleanInfoParser extends AbstractInfoDataParser {

    /** 表示为真的字符串 */
    private static final Set<String> FALSE_SET = CollUtil.newHashSet("false", "no", "0", "off", "否", "错", "假", "錯", "×");

    @Override
    protected void validateDefine(ParserResult result) {
        // 不支持区间格式
        if(result.isRegion()) {
            throw new BusinessException(StrUtil.format("信息点[{}]定义有误，Boolean类型不允许定义区间！", result.getInfoDefine().getCode()));
        }
    }

    @Override
    protected void validateValue(ParserResult result) throws IOException {
        // 复数
        if(result.isMulti()) {
            formatListValue(result.getValueInfo(), Boolean.class);
        } else {
            // 单数
            formatValue(result.getValueInfo(), Boolean.class);
        }
    }

    /**
     * 获取数据
     * @param value
     * @param clazz
     * @param <T>
     * @return
     */
    @Override
    protected <T> T formatValue(JsonNode value, Class<T> clazz) throws IOException {
        if(value == null || JsonNodeType.NULL == value.getNodeType()) {
            return null;
        }
        if (!(FALSE_SET.contains(value.asText()) || BooleanUtil.toBoolean(value.asText()))){
            throw new IOException(value.asText()+"格式有误");
        }
        return getObjectMapper().readValue(BooleanUtil.toStringTrueFalse(BooleanUtil.toBoolean(value.asText())), clazz);
    }
}
