package com.tiedup.remake.network.action;

import com.tiedup.remake.events.captivity.ForcedSeatingHandler;
import com.tiedup.remake.network.PacketRateLimiter;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet to sync Force Seat keybind state from client to server.
 *
 * When the player presses/releases the Force Seat key (default: ALT),
 * this packet is sent to update the server-side state.
 * ForcedSeatingHandler uses this state to determine if ALT+click
 * should mount/dismount captives on vehicles.
 */
public class PacketForceSeatModifier {

    private final boolean pressed;

    public PacketForceSeatModifier(boolean pressed) {
        this.pressed = pressed;
    }

    public static void encode(
        PacketForceSeatModifier packet,
        FriendlyByteBuf buf
    ) {
        buf.writeBoolean(packet.pressed);
    }

    public static PacketForceSeatModifier decode(FriendlyByteBuf buf) {
        return new PacketForceSeatModifier(buf.readBoolean());
    }

    public static void handle(
        PacketForceSeatModifier packet,
        Supplier<NetworkEvent.Context> ctx
    ) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer player = ctx.get().getSender();
                if (player != null) {
                    if (
                        !PacketRateLimiter.allowPacket(player, "action")
                    ) return;
                    ForcedSeatingHandler.setForceSeatPressed(
                        player.getUUID(),
                        packet.pressed
                    );
                }
            });
        ctx.get().setPacketHandled(true);
    }
}
