package com.tiedup.remake.network.action;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.PlayerBindState;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 *
 * Based on original PacketStruggleServer from 1.12.2
 *
 * Sent by client when player presses the struggle keybind.
 * No payload needed - just signals the server that the player wants to struggle.
 */
public class PacketStruggle {

    /**
     * Empty packet - no data needed.
     */
    public PacketStruggle() {
        // Empty packet
    }

    /**
     * Encode the packet to the network buffer.
     * Nothing to encode for this packet.
     *
     * @param buf The buffer to write to
     */
    public void encode(FriendlyByteBuf buf) {
        // Empty - no data
    }

    /**
     * Decode the packet from the network buffer.
     * Nothing to decode for this packet.
     *
     * @param buf The buffer to read from
     * @return The decoded packet
     */
    public static PacketStruggle decode(FriendlyByteBuf buf) {
        return new PacketStruggle();
    }

    /**
     * Handle the packet on the receiving side (SERVER SIDE).
     *
     * @param ctx The network context
     */
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                // This runs on the SERVER side only
                ServerPlayer player = ctx.get().getSender();
                if (player == null) {
                    return;
                }

                // Rate limiting: Prevent struggle spam
                if (
                    !com.tiedup.remake.network.PacketRateLimiter.allowPacket(
                        player,
                        "struggle"
                    )
                ) {
                    return;
                }

                handleServer(player);
            });
        ctx.get().setPacketHandled(true);
    }

    /**
     * Handle the packet on the server side.
     * Calls the player's struggle() method.
     *
     * Based on original PacketStruggleServer handler
     *
     * @param player The player who sent the packet
     */
    private void handleServer(ServerPlayer player) {
        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) {
            TiedUpMod.LOGGER.warn(
                "[PACKET] PacketStruggle received but PlayerBindState is null for {}",
                player.getName().getString()
            );
            return;
        }

        // Call struggle
        state.getStruggle().struggle();
    }
}
