package me.km.networking;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;

public class PlayerHead {
    // 1 - add - index, name, x, y, scale
    // 2 - remove - index
    // 3 - clear
    private byte action;
    private byte index;
    private String name;
    private float x;
    private float y;
    private float width;
    private float height;

    public PlayerHead() {
        action = -1;
        index = -1;
        name = "";
        x = 0.0f;
        y = 0.0f;
        width = 0.0f;
        height = 0.0f;
    }

    public PlayerHead(byte action, byte index, String name, float x, float y, float width,
            float height) {
        this.action = action;
        this.index = index;
        if(name.length() > 16) {
            this.name = name.substring(0, 16);
        } else {
            this.name = name;
        }
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public static void writeBytes(PlayerHead ph, PacketBuffer buf) {
        buf.writeByte(ph.action);
        switch(ph.action) {
            case 1:
                buf.writeFloat(ph.x);
                buf.writeFloat(ph.y);
                buf.writeFloat(ph.width);
                buf.writeFloat(ph.height);
                buf.writeByte(ph.index);
                byte[] b = ph.name.getBytes(StandardCharsets.UTF_8);
                buf.writeInt(b.length);
                buf.writeBytes(b);
                break;
            case 2:
                buf.writeByte(ph.index);
                break;
        }
    }

    public static PlayerHead fromBytes(PacketBuffer buf) {
        PlayerHead ph = new PlayerHead();
        ph.action = buf.readByte();
        switch(ph.action) {
            case 1:
                ph.x = buf.readFloat();
                ph.y = buf.readFloat();
                ph.width = buf.readFloat();
                ph.height = buf.readFloat();
                ph.index = buf.readByte();
                int length = buf.readInt();
                ph.name = buf.readBytes(length).toString(StandardCharsets.UTF_8);
                break;
            case 2:
                ph.index = buf.readByte();
                break;
        }
        return ph;
    }

    public static void handle(PlayerHead ph, Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            switch(ph.action) {
                case 1:
                    PlayerHeadGui.INSTANCE.add(ph.index, ph.x, ph.y, ph.width, ph.height, ph.name);
                    break;
                case 2:
                    PlayerHeadGui.INSTANCE.remove(ph.index);
                    break;
                case 3:
                    PlayerHeadGui.INSTANCE.clear();
                    break;
            }
        });
        context.get().setPacketHandled(true);
    }
}
