package me.km.networking;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
import me.km.inventory.CustomContainer;
import me.km.inventory.ModInventory;
import net.minecraft.client.Minecraft;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.network.NetworkEvent;

public class CustomInventory {
    private int windowId;
    private String windowTitle;
    private byte slotCount;
    private byte allSlots;
    private final byte[] data;

    public CustomInventory() {
        windowId = -1;
        windowTitle = "";
        slotCount = 9;
        allSlots = 9;
        data = new byte[14];
    }

    public CustomInventory(int id, String title, ModInventory inv) {
        windowId = id;
        windowTitle = title;
        slotCount = (byte) inv.getSizeInventory();
        allSlots = (byte) inv.getAllSlots();
        data = inv.getData();
    }

    public static void writeBytes(CustomInventory ci, PacketBuffer buf) {
        buf.writeInt(ci.windowId);
        byte[] b = ci.windowTitle.getBytes(StandardCharsets.UTF_8);
        buf.writeInt(b.length);
        buf.writeBytes(b);
        buf.writeByte(ci.slotCount);
        buf.writeByte(ci.allSlots);
        buf.writeBytes(ci.data);
    }

    public static CustomInventory fromBytes(PacketBuffer buf) {
        CustomInventory ci = new CustomInventory();
        ci.windowId = buf.readInt();
        int length = buf.readInt();
        ci.windowTitle = buf.readBytes(length).toString(StandardCharsets.UTF_8);
        ci.slotCount = buf.readByte();
        ci.allSlots = buf.readByte();
        for(int i = 0; i < 14; i++) {
            ci.data[i] = buf.readByte();
        }
        return ci;
    }

    public static void handle(CustomInventory ci, Supplier<NetworkEvent.Context> context) {
        // prevent error on loading the class on the server
        handleIntern(ci, context);
    }

    @OnlyIn(Dist.CLIENT)
    private static void handleIntern(CustomInventory ci, Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            Minecraft mc = Minecraft.getInstance();
            CustomContainer cc = new CustomContainer(ci.windowId, mc.player.inventory, new ModInventory(ci.data, ci.slotCount, ci.allSlots));
            mc.player.openContainer = cc;
            mc.displayGuiScreen(new CustomInventoryScreen(cc, mc.player.inventory, new StringTextComponent(ci.windowTitle)));
        });
        context.get().setPacketHandled(true);
    }
}
