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

import com.lingniu.ingest.codec.BcdCodec;
import com.lingniu.ingest.protocol.jt1078.model.Jt1078MessageId;
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 java.nio.ByteBuffer;

/** 0x1005 终端上传乘客流量，字段结构化后仍按可查询透传事件入库。 */
public final class PassengerVolumeBodyParser implements BodyParser {
    @Override public int messageId() { return Jt1078MessageId.TERMINAL_PASSENGER_VOLUME; }

    @Override
    public Jt808Body parse(Jt808Header header, ByteBuffer body) {
        byte[] raw = new byte[body.remaining()];
        body.get(raw);
        ByteBuffer b = ByteBuffer.wrap(raw);
        return new Jt808Body.PassengerVolume(
                readU8(b),
                readBcdTime(b),
                readBcdTime(b),
                readU16(b),
                readU16(b),
                raw);
    }

    private static int readU8(ByteBuffer b) {
        return b.hasRemaining() ? b.get() & 0xFF : 0;
    }

    private static int readU16(ByteBuffer b) {
        return b.remaining() >= 2 ? b.getShort() & 0xFFFF : 0;
    }

    private static String readBcdTime(ByteBuffer b) {
        if (b.remaining() < 6) {
            byte[] tail = new byte[b.remaining()];
            b.get(tail);
            return "";
        }
        byte[] time = new byte[6];
        b.get(time);
        String ts = BcdCodec.decode(time);
        if (ts.length() != 12) {
            return "";
        }
        return "20" + ts.substring(0, 2)
                + "-" + ts.substring(2, 4)
                + "-" + ts.substring(4, 6)
                + "T" + ts.substring(6, 8)
                + ":" + ts.substring(8, 10)
                + ":" + ts.substring(10, 12);
    }
}
