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 ItemStackDisplay {
    private byte index;
    private String name;

    public ItemStackDisplay() {
        index = -1;
        name = "";
    }

    public ItemStackDisplay(byte index, String name) {
        this.index = index;
        this.name = name;
    }

    public static void writeBytes(ItemStackDisplay isd, PacketBuffer buf) {
        buf.writeByte(isd.index);
        byte[] b = isd.name.getBytes(StandardCharsets.UTF_8);
        buf.writeInt(b.length);
        buf.writeBytes(b);
    }

    public static ItemStackDisplay fromBytes(PacketBuffer buf) {
        ItemStackDisplay isd = new ItemStackDisplay();
        isd.index = buf.readByte();
        int length = buf.readInt();
        isd.name = buf.readBytes(length).toString(StandardCharsets.UTF_8);
        return isd;
    }

    public static void handle(ItemStackDisplay isd, Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            switch(isd.index) {
                case -1:
                    ItemStackDisplayGui.INSTANCE.setActive(true);
                    break;
                case -2:
                    ItemStackDisplayGui.INSTANCE.setActive(false);
                    break;
                case -3:
                    ItemStackDisplayGui.INSTANCE.clear();
                    break;
                default:
                    ItemStackDisplayGui.INSTANCE.setIcon(isd.index, isd.name);
                    break;
            }
        });
        context.get().setPacketHandled(true);
    }
}
