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

import com.lingniu.ingest.protocol.gb32960.codec.InfoBlockParser;
import com.lingniu.ingest.protocol.gb32960.codec.ValueDecoder;
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;

/**
 * 超级电容器数据 (0x31) —— GB/T 32960.3-2025 §7.2.4.10 表 25。变长。
 */
public final class SuperCapacitorV2025BlockParser implements InfoBlockParser {

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

    @Override
    public InfoBlock parse(ByteBuffer buf) {
        int systemNo = buf.get() & 0xFF;
        Double totalVoltage = ValueDecoder.scaledU16(buf, 0.1);
        Double totalCurrent = ValueDecoder.scaledU16WithOffset(buf, 0.1, -3000.0);
        int cellCount = buf.getShort() & 0xFFFF;
        List<Double> cells = new ArrayList<>(cellCount);
        // 电压数组按 2 字节一个值裁剪，避免声明数量异常时读穿温度段。
        int safeCellCount = Math.min(cellCount, buf.remaining() / 2);
        for (int i = 0; i < safeCellCount; i++) {
            cells.add((buf.getShort() & 0xFFFF) * 0.001);
        }
        int probeCount = buf.hasRemaining() ? (buf.getShort() & 0xFFFF) : 0;
        List<Integer> temps = new ArrayList<>(probeCount);
        // 温度探针每个 1 字节，按剩余字节裁剪。
        int safeProbeCount = Math.min(probeCount, buf.remaining());
        for (int i = 0; i < safeProbeCount; i++) {
            temps.add((buf.get() & 0xFF) - 40);
        }
        return new InfoBlock.Gb32960V2025.SuperCapacitor(systemNo, totalVoltage, totalCurrent, cells, temps);
    }
}
