package com.lingniu.ingest.protocol.jsatl12.codec;

import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.buffer.Unpooled;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;

import static org.assertj.core.api.Assertions.assertThat;

class Jsatl12DataPacketDecoderTest {

    @Test
    void dataPacketUsesFilenameOffsetLengthLayoutInsteadOfMagicLengthLayout() {
        EmbeddedChannel channel = new EmbeddedChannel(new Jsatl12FrameDecoder(128));
        byte[] packet = dataPacket("ADAS_001.jpg", 3, new byte[]{0x04, 0x05, 0x06});

        channel.writeInbound(Unpooled.wrappedBuffer(packet));

        Jsatl12RawFrame frame = channel.readInbound();
        assertThat(frame.type()).isEqualTo(Jsatl12RawFrame.Type.DATA_CHUNK);
        assertThat(frame.bytes()).containsExactly(packet);
        Object next = channel.readInbound();
        assertThat(next).isNull();
    }

    private static byte[] dataPacket(String name, int offset, byte[] data) {
        byte[] out = new byte[62 + data.length];
        out[0] = 0x30;
        out[1] = 0x31;
        out[2] = 0x63;
        out[3] = 0x64;
        byte[] nameBytes = name.getBytes(StandardCharsets.US_ASCII);
        System.arraycopy(nameBytes, 0, out, 4, nameBytes.length);
        writeDword(out, 54, offset);
        writeDword(out, 58, data.length);
        System.arraycopy(data, 0, out, 62, data.length);
        return out;
    }

    private static void writeDword(byte[] out, int offset, long value) {
        out[offset] = (byte) ((value >>> 24) & 0xFF);
        out[offset + 1] = (byte) ((value >>> 16) & 0xFF);
        out[offset + 2] = (byte) ((value >>> 8) & 0xFF);
        out[offset + 3] = (byte) (value & 0xFF);
    }
}
