package com.lingniu.ingest.protocol.gb32960.codec.parser.vendor.guangdong;

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;

/**
 * 广东燃料电池规范 §7.2.3.14 表 27：燃料电池汽车示范应用数据扩展。typeCode {@code 0x80}。
 *
 * <p>结构（typeCode 由外层消费）：
 * <pre>
 *   dataLength (2B WORD) = 9     表示后续扩展数据长度
 *   stackTempC (1B, -40 offset, -40~+210°C)
 *   airCompressorVoltageV (2B, 0.1V, 0~2000V)
 *   airCompressorCurrentA (2B, 0.1A, -1000 offset, -1000~+1000A)
 *   hydrogenPumpVoltageV (2B, 0.1V, 0~2000V)
 *   hydrogenPumpCurrentA (2B, 0.1A, -1000 offset, -1000~+1000A)
 * </pre>
 *
 * 含 length 字段共 11 字节 body（不含外层 1B typeCode）。
 */
public final class GdFcDemoExtensionBlockParser implements InfoBlockParser {

    @Override public ProtocolVersion version() { return ProtocolVersion.V2016; }
    @Override public int typeCode() { return 0x80; }
    @Override public int fixedLength() { return 11; }

    @Override
    public InfoBlock parse(ByteBuffer buf) {
        int declaredLen = buf.getShort() & 0xFFFF;
        // declaredLen 通常 = 9，但即便不是也按 9 字节固定布局解，避免无谓的失败。
        Integer stackTemp = ValueDecoder.tempOffset40(buf);
        Double acV = ValueDecoder.scaledU16(buf, 0.1);
        Double acC = ValueDecoder.scaledU16WithOffset(buf, 0.1, -1000.0);
        Double h2V = ValueDecoder.scaledU16(buf, 0.1);
        Double h2C = ValueDecoder.scaledU16WithOffset(buf, 0.1, -1000.0);
        // 防御：若 declaredLen 与实际不一致，仅在 DEBUG 留痕。
        if (declaredLen != 9 && org.slf4j.LoggerFactory.getLogger(GdFcDemoExtensionBlockParser.class).isDebugEnabled()) {
            org.slf4j.LoggerFactory.getLogger(GdFcDemoExtensionBlockParser.class)
                    .debug("[gb32960/gd-fc/0x80] declaredLen={} (expected 9), parsed by fixed layout", declaredLen);
        }
        return new InfoBlock.GuangdongFc.DemoExtension(stackTemp, acV, acC, h2V, h2C);
    }
}
