package com.lingniu.ingest.protocol.jt808.codec.parser;

import com.lingniu.ingest.protocol.jt808.codec.BodyParser;
import com.lingniu.ingest.protocol.jt808.model.Jt808Body;
import com.lingniu.ingest.protocol.jt808.model.Jt808Header;
import com.lingniu.ingest.protocol.jt808.model.Jt808MessageId;

import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.Map;

public final class TerminalParamsReportBodyParser implements BodyParser {

    @Override
    public int messageId() {
        return Jt808MessageId.TERMINAL_PARAMS_REPORT;
    }

    @Override
    public Jt808Body parse(Jt808Header header, ByteBuffer body) {
        int responseSerialNo = body.remaining() >= 2 ? body.getShort() & 0xFFFF : 0;
        int count = body.remaining() >= 1 ? body.get() & 0xFF : 0;
        Map<Long, byte[]> parameters = new LinkedHashMap<>();
        for (int i = 0; i < count && body.remaining() >= 5; i++) {
            long paramId = body.getInt() & 0xFFFFFFFFL;
            int len = body.get() & 0xFF;
            if (len > body.remaining()) {
                len = body.remaining();
            }
            byte[] value = new byte[len];
            body.get(value);
            parameters.put(paramId, value);
        }
        return new Jt808Body.ParamsReport(responseSerialNo, Map.copyOf(parameters));
    }
}
