package me.koba1.led.device.packets;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public abstract class Packet {
    @Getter
    @AllArgsConstructor
    public static enum PacketType {
        READY(1),
        ERROR(3),
        TEST_CONNECTION(0),
        UPDATE_LEDSTRIPS(2),
        UPDATE_COLORS(4),
        ;
        private final byte id;
        PacketType(int id) {
            this.id = (byte) id;
        }
    }
    //public final static byte MAGIC_NUMBER = (byte) 0xABCD;
    public static final short MAGIC = (short) 0xABCD;
    public static final byte[] MAGIC_REVERSED = {(byte) 0xDC, (byte) 0xBA};

    public abstract byte getPacketId();
    protected abstract byte[] getPayload();

    public byte[] toBytes() {
        byte[] payload = getPayload();
        short length = (short) (1 + payload.length); // id (1 byte) + payload (N byte)

        // 2 byte magic, 2 byte packet length, payload length
        ByteBuffer buffer = ByteBuffer.allocate(2 + 2 + length).order(ByteOrder.LITTLE_ENDIAN); // ALAPBOL BIG ENDIAN

        buffer.putShort(MAGIC);

        buffer.putShort(length);
        buffer.put(getPacketId());
        buffer.put(payload);

        return buffer.array();
    }
}

/*
🧠 Mikor jó a ByteArrayOutputStream?
Akkor ha:
nem tudod előre a méretet
streaming adatot írsz
file vagy network stream
De protokoll packet építéshez → ByteBuffer jobb.
 */
