package me.koba1.led.device.packets;

import io.netty.buffer.ByteBuf;
import me.koba1.led.model.colors.KobaOutputColor;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;

public class UpdateColorPacket extends Packet {
    @Override
    public byte getPacketId() {
        return PacketType.UPDATE_COLORS.getId();
    }

    //        strip id      led id      color
    private final Map<Integer, Map<Integer, Integer>> colorData;

    public UpdateColorPacket(Map<Integer, KobaOutputColor> colorData) {
        Map<Integer, Map<Integer, Integer>> intColors = new HashMap<>();
        for (Map.Entry<Integer, KobaOutputColor> entry : colorData.entrySet()) {
            intColors.put(entry.getKey(), entry.getValue().getIntegerColors());
        }
        this.colorData = intColors;
    }

    @Override
    protected byte[] getPayload() {
        int byteCount = 1; // ledstrip darabszám
        for (Map.Entry<Integer, Map<Integer, Integer>> ledStripColors : this.colorData.entrySet()) {
            byteCount += 1 + 2 + ledStripColors.getValue().size() * 6; // id + color darabszám + colors (pixel short2 + color int4)
        }

        ByteBuffer buffer = ByteBuffer.allocate(byteCount).order(ByteOrder.LITTLE_ENDIAN);
        buffer.put((byte) this.colorData.size());

        // id, color size, color
        for (Map.Entry<Integer, Map<Integer, Integer>> ledStrip : this.colorData.entrySet()) {
            buffer.put(ledStrip.getKey().byteValue()); // id
            // color length
            buffer.putShort((short) ledStrip.getValue().size());

            for (Map.Entry<Integer, Integer> color : ledStrip.getValue().entrySet()) {
                int rgba = color.getValue();
                buffer.putShort(color.getKey().shortValue());
//                buffer.order(ByteOrder.BIG_ENDIAN);
//                buffer.putInt(color.getValue());
//                buffer.order(ByteOrder.LITTLE_ENDIAN);
                buffer.put((byte)((rgba >>> 24) & 0xFF));
                buffer.put((byte)((rgba >>> 16) & 0xFF));
                buffer.put((byte)((rgba >>>  8) & 0xFF));
                buffer.put((byte)( rgba         & 0xFF));
            }
        }
        return buffer.array();
    }
}
