/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.core.network.toClient;

import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.eroticdungeongame.util.IEDGClientPacketListener;

import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;

public record NPCInfoRemovePacket(List<UUID> profileIds) {
    public NPCInfoRemovePacket(@NotNull FriendlyByteBuf buf) {
        this(buf.readList(FriendlyByteBuf::readUUID));
    }

    public void write(@NotNull FriendlyByteBuf buffer) {
        buffer.writeCollection(this.profileIds, FriendlyByteBuf::writeUUID);
    }


    public static void handle(NPCInfoRemovePacket packet, @NotNull Supplier<NetworkEvent.Context> contextSupplier) {
        NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            for(UUID uuid : packet.profileIds()) {
                Minecraft minecraft = Minecraft.getInstance();
                ClientPacketListener clientPacketListener = minecraft.getConnection();
                if(clientPacketListener instanceof IEDGClientPacketListener iedgClientPacketListener) {
                    PlayerInfo playerinfo = iedgClientPacketListener.getNPCPlayerInfoMap().remove(uuid);
                    if (playerinfo != null) {
                        iedgClientPacketListener.getListedNPCPlayers().remove(playerinfo);
                    }
                }
            }
        });
        context.setPacketHandled(true);
    }
}
