package com.huimv.admin.server;

// ---------------------- 解析工具类 ----------------------
class HJ212Parser {
    
    public static EnvironmentalData parse(String rawData) {
        EnvironmentalData result = new EnvironmentalData();
        String[] parts = rawData.split(";");

        // 1. 解析基础头信息
        Header header = new Header();
        for (String part : parts) {
            if (part.contains("=")) {
                String[] kv = part.split("=", 2);
                String key = kv[0].trim();
                String value = kv[1].trim();
                switch (key) {
                    case "QN": header.setQn(value); break;
                    case "ST": header.setSt(value); break;
                    case "CN": header.setCn(value); break;
                    case "PW": header.setPw(value); break;
                    case "MN": header.setMn(value); break;
                    case "Flag": header.setFlag(value); break;
                }
            }
        }
        result.setHeader(header);

        // 2. 解析CP段
        CPData cpData = new CPData();
        String cpContent = rawData.split("CP=&&")[1].split("&&")[0];
        String[] cpItems = cpContent.split(";");
        
        for (String item : cpItems) {
            if (item.startsWith("DataTime=")) {
                cpData.setDataTime(item.split("=")[1]);
            } else {
                parseParameter(item, cpData);
            }
        }
        result.setCpData(cpData);

        // 3. 解析TTL
        String ttlPart = rawData.split("&&")[2].trim();
        result.setTtl(Integer.parseInt(ttlPart.split(" ")[0]));
        
        return result;
    }
    private static void parseParameter(String item, CPData cpData) {
        String[] pairs = item.split(",");
        Parameter param = new Parameter();
        String code = null;

        for (String pair : pairs) {
            String[] kv = pair.split("=");
            String key = kv[0].trim();
            String value = kv[1].trim();

            if (key.contains("-")) {
                code = key.split("-")[0];
                String field = key.split("-")[1];
                switch (field) {
                    case "Min": param.setMin(value); break;
                    case "Max": param.setMax(value); break;
                    case "Avg": param.setAvg(value); break;
                    case "Cou": param.setCou(value); break;
                    case "Flag": param.setFlag(value); break;
                }
            }
        }

        if (code != null) {
            cpData.addParameter(code, param);
        }
    }
}