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.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class AuthBodyParser implements BodyParser {

    private static final Pattern IMEI = Pattern.compile("(?<!\\d)(\\d{15})(?!\\d)");

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

    @Override
    public Jt808Body parse(Jt808Header header, ByteBuffer buf) {
        byte[] raw = new byte[buf.remaining()];
        buf.get(raw);
        String token = new String(raw, StandardCharsets.UTF_8)
                .replace("\u0000", "")
                .trim();
        Matcher matcher = IMEI.matcher(token);
        String imei = matcher.find() ? matcher.group(1) : "";
        String softwareVersion = softwareVersion(token, imei);
        return new Jt808Body.Auth(token, imei, softwareVersion);
    }

    private static String softwareVersion(String token, String imei) {
        if (imei.isBlank()) {
            return "";
        }
        int pos = token.indexOf(imei);
        if (pos < 0) {
            return "";
        }
        String tail = token.substring(pos + imei.length()).trim();
        while (tail.startsWith(",") || tail.startsWith(";") || tail.startsWith("|")) {
            tail = tail.substring(1).trim();
        }
        return tail;
    }
}
