package dev.micle.loginprotection.network.server;

import dev.micle.loginprotection.events.client.OnClientInputEventHandler;
import dev.micle.loginprotection.network.NetworkManager;
import dev.micle.loginprotection.network.client.LastInputTickPacket;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class RequestLastInputTickPacket {
    public static void encode(final RequestLastInputTickPacket packet, final FriendlyByteBuf buffer) {
        NetworkManager.writeVersionInfo(buffer, false);
    }

    public static RequestLastInputTickPacket decode(final FriendlyByteBuf buffer) {
        NetworkManager.checkVersion(buffer);
        return new RequestLastInputTickPacket();
    }

    public static void handle(final RequestLastInputTickPacket packet, final Supplier<NetworkEvent.Context> contextSupplier) {
        final NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            // Update last input tick (This works around GLFW forgetting about a repeat key after another one is pressed)
            OnClientInputEventHandler.checkIfInputIsAllowed();

            // Send last input tick packet back to server
            NetworkManager.getChannel().sendToServer(new LastInputTickPacket());
        });
        context.setPacketHandled(true);
    }
}
