package com.lingniu.ingest.protocol.gb32960.codec.parser.v2016;

import com.lingniu.ingest.protocol.gb32960.codec.InfoBlockParser;
import com.lingniu.ingest.protocol.gb32960.model.InfoBlock;
import com.lingniu.ingest.protocol.gb32960.model.ProtocolVersion;

import java.nio.ByteBuffer;

/**
 * 可充电储能装置温度数据 (0x09) —— GB/T 32960.3-2016 表 B.20。变长。
 * subSystemCount(1) + 每子系统 [batteryIndex(1) + probeCount(2) + probes(probeCount*1,-40 offset)]。
 *
 * <p>2025 版已删除该 typeCode（动力蓄电池温度改用 0x08）。
 */
public final class TemperatureV2016BlockParser implements InfoBlockParser {

    @Override public ProtocolVersion version() { return ProtocolVersion.V2016; }
    @Override public int typeCode() { return 0x09; }
    @Override public int fixedLength() { return -1; }

    @Override
    public InfoBlock parse(ByteBuffer buf) {
        int subCount = buf.get() & 0xFF;
        int maxT = Integer.MIN_VALUE;
        int minT = Integer.MAX_VALUE;
        for (int i = 0; i < subCount; i++) {
            buf.get(); // batteryIndex
            int probes = buf.getShort() & 0xFFFF;
            // 与电压块类似，这里暂不保存每个探针，只输出可查询的最高/最低温摘要。
            for (int p = 0; p < probes; p++) {
                int t = (buf.get() & 0xFF) - 40;
                if (t > maxT) maxT = t;
                if (t < minT) minT = t;
            }
        }
        if (maxT == Integer.MIN_VALUE) maxT = 0;
        if (minT == Integer.MAX_VALUE) minT = 0;
        return new InfoBlock.Gb32960V2016.Temperature(subCount, maxT, minT);
    }
}
