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.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 0x0100 终端注册。
 *
 * <p>2013 body 格式：
 * <pre>
 *   provinceId(2)
 *   cityId(2)
 *   makerId(5 ASCII)
 *   deviceType(20 ASCII) -- 2011 版为 8
 *   deviceId(7 ASCII)
 *   plateColor(1)
 *   plate(GBK, 剩余全部字节)
 * </pre>
 */
public final class RegisterBodyParser implements BodyParser {

    private static final Charset GBK = Charset.forName("GBK");

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

    @Override
    public Jt808Body parse(Jt808Header header, ByteBuffer buf) {
        int province = buf.getShort() & 0xFFFF;
        int city = buf.getShort() & 0xFFFF;
        String maker = readAscii(buf, 5);
        String deviceType = readAscii(buf, 20);
        String deviceId = readAscii(buf, 7);
        int plateColor = buf.get() & 0xFF;
        byte[] plateBytes = new byte[buf.remaining()];
        buf.get(plateBytes);
        String plate = new String(plateBytes, GBK).trim();
        return new Jt808Body.Register(province, city, maker, deviceType, deviceId, plateColor, plate);
    }

    private static String readAscii(ByteBuffer buf, int len) {
        byte[] b = new byte[len];
        buf.get(b);
        return new String(b, StandardCharsets.US_ASCII).trim();
    }
}
