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

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;
import java.util.ArrayList;
import java.util.List;

/**
 * 动力蓄电池温度数据 (0x08) —— GB/T 32960.3-2025 §7.2.4.3。变长。
 * 2016 版 0x08 为可充电储能装置电压，由 v2016 包处理。
 */
public final class BatteryTemperatureV2025BlockParser implements InfoBlockParser {

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

    @Override
    public InfoBlock parse(ByteBuffer buf) {
        int subCount = buf.get() & 0xFF;
        List<InfoBlock.Gb32960V2025.BatteryTemperature.Pack> packs = new ArrayList<>(subCount);
        for (int i = 0; i < subCount; i++) {
            int packNo = buf.get() & 0xFF;
            int probeCount = buf.getShort() & 0xFFFF;
            List<Integer> temps = new ArrayList<>(probeCount);
            // probeCount 是车端声明值；实际数组按剩余字节裁剪，防止坏包读穿。
            int safeCount = Math.min(probeCount, buf.remaining());
            for (int k = 0; k < safeCount; k++) {
                temps.add((buf.get() & 0xFF) - 40);
            }
            packs.add(new InfoBlock.Gb32960V2025.BatteryTemperature.Pack(packNo, probeCount, temps));
        }
        return new InfoBlock.Gb32960V2025.BatteryTemperature(subCount, packs);
    }
}
