/*
 *  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.mixin.minecraft;

import com.google.common.collect.Lists;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import top.r3944realms.eroticdungeongame.content.entity.npc.NPCPlayerList;
import top.r3944realms.eroticdungeongame.content.entity.npc.NPCServerPlayer;
import top.r3944realms.eroticdungeongame.util.IEDGMinecraftServer;

import javax.annotation.Nullable;
import java.util.UUID;

@Mixin(IntegratedServer.class)
public abstract class MixinIntegratedServer implements IEDGMinecraftServer {
    @Shadow @Nullable private UUID uuid;

    @Inject(
            method = "<init>",
            at = @At("TAIL")
    )
    private void edg$init(CallbackInfo ci) {
        IntegratedServer server = IntegratedServer.class.cast(this);
        setNPCPlayerList(new NPCPlayerList(server, server.registries(), getNPCDataStorage()));
    }
    @WrapOperation(
            method = "halt",
            at = @At(
                    value = "INVOKE",
                    target = "Lnet/minecraft/client/server/IntegratedServer;executeBlocking(Ljava/lang/Runnable;)V"
            )
    )
    private void edg$halt$3$removeNpc(IntegratedServer instance, Runnable runnable, @NotNull Operation<Void> original) {
        original.call(instance, runnable);
        original.call(instance, (Runnable) () -> {
            for(NPCServerPlayer npcServerPlayer : Lists.newArrayList(getNPCPlayerList().getPlayers())) {
                if (!npcServerPlayer.getUUID().equals(this.uuid)) {
                    getNPCPlayerList().remove(npcServerPlayer);
                }
            }
        });
    }
}
