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;

public final class MediaUploadBodyParser implements BodyParser {

    private final LocationBodyParser locationParser = new LocationBodyParser();

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

    @Override
    public Jt808Body parse(Jt808Header header, ByteBuffer body) {
        long mediaId = body.remaining() >= 4 ? body.getInt() & 0xFFFFFFFFL : 0;
        int mediaType = body.hasRemaining() ? body.get() & 0xFF : 0;
        int mediaFormat = body.hasRemaining() ? body.get() & 0xFF : 0;
        int eventCode = body.hasRemaining() ? body.get() & 0xFF : 0;
        int channelId = body.hasRemaining() ? body.get() & 0xFF : 0;
        Jt808Body.Location location = null;
        if (body.remaining() >= 28) {
            ByteBuffer loc = body.slice(body.position(), 28);
            if (locationParser.parse(header, loc) instanceof Jt808Body.Location parsed) {
                location = parsed;
            }
            body.position(body.position() + 28);
        }
        byte[] data = new byte[body.remaining()];
        body.get(data);
        return new Jt808Body.MediaUpload(mediaId, mediaType, mediaFormat, eventCode, channelId, location, data);
    }
}
