package com.yice.webadmin.app.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yice.webadmin.app.constant.DatasetConstant;
import com.yice.webadmin.app.data.DatasetRule;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class JsonNameExtractor {

    /**
     * 拼接名字
     * @param jsonStrings json名字
     * @return 名字列表
     */
    public static List<String> extractNames(List<String> jsonStrings) {
        ObjectMapper mapper = new ObjectMapper();
        List<String> names = new ArrayList<>();
        for (String jsonString : jsonStrings) {
            try {
                JsonNode rootNode = mapper.readTree(jsonString);
                if (rootNode.isArray()) {
                    for (JsonNode jsonNode : rootNode) {
                        JsonNode nameNode = jsonNode.get("name");
                        if (nameNode != null && nameNode.isTextual()) {
                            names.add(nameNode.asText());
                        }
                    }
                }
            } catch (IOException e) {
                log.error("extract name is error", e);
                continue;
            }
        }
        return names;
    }

    /**
     * 拼接名字
     * @param rule json名字
     * @return 名字列表
     */
    public static List<String> extractNames(String rule) {
        ObjectMapper mapper = new ObjectMapper();
        List<String> names = new ArrayList<>();
        try {
            JsonNode rootNode = mapper.readTree(rule);
            if (rootNode.isArray()) {
                for (JsonNode jsonNode : rootNode) {
                    JsonNode nameNode = jsonNode.get("name");
                    if (nameNode != null && nameNode.isTextual()) {
                        names.add(nameNode.asText());
                    }
                }
            }
        } catch (IOException e) {
            log.error("extract name method overload is error", e);
        }
        return names;
    }

    /**
     * 拼接名字
     * @param rule json名字
     * @return 名字列表
     */
    public static DatasetRule buildRuleData(String rule) {
        DatasetRule datasetRule = new DatasetRule();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode config = objectMapper.readTree(rule);
            String args = config.get(DatasetConstant.ARGS).textValue();
            datasetRule.setArgs(Double.valueOf(args));
            String name = config.get(DatasetConstant.NAME).textValue();
            datasetRule.setName(name);
        } catch (IOException e) {
            log.error("extract name method overload is error", e);
        }
        return datasetRule;
    }

}
