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

public final class LocationBatchBodyParser implements BodyParser {

    private final LocationBodyParser locationParser = new LocationBodyParser();

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

    @Override
    public Jt808Body parse(Jt808Header header, ByteBuffer body) {
        int count = body.remaining() >= 2 ? body.getShort() & 0xFFFF : 0;
        int batchType = body.remaining() >= 1 ? body.get() & 0xFF : 0;
        List<Jt808Body.Location> locations = new ArrayList<>(count);
        for (int i = 0; i < count && body.remaining() >= 2; i++) {
            int len = body.getShort() & 0xFFFF;
            if (len > body.remaining()) {
                len = body.remaining();
            }
            ByteBuffer slice = body.slice(body.position(), len);
            Jt808Body parsed = locationParser.parse(header, slice);
            if (parsed instanceof Jt808Body.Location location) {
                locations.add(location);
            }
            body.position(body.position() + len);
        }
        return new Jt808Body.LocationBatch(batchType, List.copyOf(locations));
    }
}
