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

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

    public StatusDisplay(byte action, byte index, int time, String text) {
        this.action = action;
        this.index = index;
        this.time = time;
        if(text.length() > 32) {
            this.text = text.substring(0, 32);
        } else {
            this.text = text;
        }
    }

    public StatusDisplay(byte action, byte index, String text) {
        this(action, index, Integer.MAX_VALUE, text);
    }

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

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

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