package com.tiedup.remake.network.cell;

import com.tiedup.remake.cells.CellDataV2;
import com.tiedup.remake.cells.CellRegistryV2;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.PacketRateLimiter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet to request the list of cells owned by the player.
 * Used to populate the CellSelectorScreen.
 *
 * Client -> Server (triggers PacketOpenCellSelector response)
 */
public class PacketRequestCellList {

    private final UUID targetEntityUUID; // The entity whose collar we want to assign

    public PacketRequestCellList(UUID targetEntityUUID) {
        this.targetEntityUUID = targetEntityUUID;
    }

    public static void encode(PacketRequestCellList msg, FriendlyByteBuf buf) {
        buf.writeUUID(msg.targetEntityUUID);
    }

    public static PacketRequestCellList decode(FriendlyByteBuf buf) {
        UUID targetEntityUUID = buf.readUUID();
        return new PacketRequestCellList(targetEntityUUID);
    }

    public static void handle(
        PacketRequestCellList msg,
        Supplier<NetworkEvent.Context> ctx
    ) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer sender = ctx.get().getSender();
                if (sender == null) return;
                if (!PacketRateLimiter.allowPacket(sender, "ui")) return;

                CellRegistryV2 registry = CellRegistryV2.get(
                    sender.serverLevel()
                );
                List<CellDataV2> playerCells = registry.getCellsByOwner(
                    sender.getUUID()
                );

                // Build cell list for packet
                List<PacketOpenCellSelector.CellOption> options =
                    new ArrayList<>();
                for (CellDataV2 cell : playerCells) {
                    String displayName =
                        cell.getName() != null
                            ? cell.getName()
                            : "Cell " + cell.getId().toString().substring(0, 8);

                    options.add(
                        new PacketOpenCellSelector.CellOption(
                            cell.getId(),
                            displayName,
                            cell.getPrisonerCount(),
                            4 // MAX_PRISONERS
                        )
                    );
                }

                // Send response packet to open the selector
                ModNetwork.sendToPlayer(
                    new PacketOpenCellSelector(msg.targetEntityUUID, options),
                    sender
                );

                TiedUpMod.LOGGER.debug(
                    "[PacketRequestCellList] Sent {} cells to {}",
                    options.size(),
                    sender.getName().getString()
                );
            });

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