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

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;
// ProtocolVersion still used by version() override below

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * 报警数据 (0x07) —— GB/T 32960.3-2016 附录 B 表 B.17。变长。
 * maxAlarmLevel(1) + generalAlarmFlag(4) + 4 组故障列表(count(1)+entries(4*N))。
 *
 * <p>2025 版报警数据 typeCode 改为 0x06 且尾部多 N5 个 (flagBit,level) —— 见 v2025 包。
 */
public final class AlarmV2016BlockParser implements InfoBlockParser {

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

    @Override
    public InfoBlock parse(ByteBuffer buf) {
        Integer maxLevel = ValueDecoder.u8(buf);
        long generalFlag = ValueDecoder.u32raw(buf);
        List<Long> battery = readFaultList(buf);
        List<Long> motor = readFaultList(buf);
        List<Long> engine = readFaultList(buf);
        List<Long> other = readFaultList(buf);
        return new InfoBlock.Gb32960V2016.Alarm(
                maxLevel, generalFlag, battery, motor, engine, other);
    }

    static List<Long> readFaultList(ByteBuffer buf) {
        int count = buf.get() & 0xFF;
        List<Long> out = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            // 故障码按 4 字节无符号值处理，避免高位为 1 时变成负数。
            out.add(buf.getInt() & 0xFFFFFFFFL);
        }
        return out;
    }
}
