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 PlayerDisplay {
    // 1 - add - index, text
    // 2 - remove - index
    // 3 - clear
    private byte action;
    private byte index;
    private String text;

    public PlayerDisplay() {
        action = -1;
        index = -1;
        text = "";
    }

    public PlayerDisplay(byte action, byte index, String text) {
        this.action = action;
        this.index = index;
        this.text = text;
    }

    public static void writeBytes(PlayerDisplay pd, PacketBuffer buf) {
        buf.writeByte(pd.action);
        buf.writeByte(pd.index);
        byte[] b = pd.text.getBytes(StandardCharsets.UTF_8);
        buf.writeInt(b.length);
        buf.writeBytes(b);
    }

    public static PlayerDisplay fromBytes(PacketBuffer buf) {
        PlayerDisplay pd = new PlayerDisplay();
        pd.action = buf.readByte();
        pd.index = buf.readByte();
        int length = buf.readInt();
        pd.text = buf.readBytes(length).toString(StandardCharsets.UTF_8);
        return pd;
    }

    public static void handle(PlayerDisplay pd, Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            switch(pd.action) {
                case 1:
                    PlayerDisplayGui.INSTANCE.add(pd.index, pd.text);
                    break;
                case 2:
                    PlayerDisplayGui.INSTANCE.remove(pd.index);
                    break;
                case 3:
                    PlayerDisplayGui.INSTANCE.clear();
                    break;
            }
        });
        context.get().setPacketHandled(true);
    }
}
