package com.xfestudio.mydimensionlord.network;

import com.xfestudio.mydimensionlord.MyDimension;
import com.xfestudio.mydimensionlord.builder.BuilderNetworkBridge;
import com.xfestudio.mydimensionlord.builder.anchor.AnchorBindings;
import com.xfestudio.mydimensionlord.network.blueprint.BlueprintNetworkRegistration;
import com.xfestudio.mydimensionlord.network.builder.BuilderNetworkRegistration;
import com.xfestudio.mydimensionlord.network.builder.BuilderOpenMenuPacket;
import com.xfestudio.mydimensionlord.network.builder.BuilderPreviewPacket;
import com.xfestudio.mydimensionlord.network.builder.BuilderSnapshotPacket;
import com.xfestudio.mydimensionlord.registry.ModItems;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.UUID;

public final class ModNetwork {
    private static final String PROTOCOL_VERSION = "1";
    public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(
            new ResourceLocation(MyDimension.MOD_ID, "main"), () -> PROTOCOL_VERSION,
            PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals);
    public static void register() {
        int id = BuilderNetworkRegistration.register(CHANNEL, 0);
        BlueprintNetworkRegistration.register(CHANNEL, id);
        BuilderNetworkBridge.install(ModNetwork::sendBuilderOpenMenu, ModNetwork::sendBuilderState);
    }

    /** Opens only after the common-side caller has proved the player is holding the scepter. */
    public static void sendBuilderOpenMenu(ServerPlayer player) {
        if (!player.getMainHandItem().is(ModItems.REALMWRIGHT_SCEPTER.get())) return;
        CHANNEL.send(PacketDistributor.PLAYER.with(() -> player), new BuilderOpenMenuPacket());
        sendBuilderState(player);
    }

    /** Sends a matched UI snapshot and missing-material preview for the main-hand scepter. */
    public static void sendBuilderState(ServerPlayer player) {
        if (!player.getMainHandItem().is(ModItems.REALMWRIGHT_SCEPTER.get())) return;
        sendBuilderSnapshot(player);
        CHANNEL.send(PacketDistributor.PLAYER.with(() -> player),
                BuilderPreviewPacket.from(player, player.getMainHandItem()));
    }

    /** Lightweight metadata refresh used by the open screen's periodic poll. */
    public static void sendBuilderSnapshot(ServerPlayer player) {
        if (!player.getMainHandItem().is(ModItems.REALMWRIGHT_SCEPTER.get())) return;
        CHANNEL.send(PacketDistributor.PLAYER.with(() -> player),
                BuilderSnapshotPacket.from(player, player.getMainHandItem()));
    }

    /**
     * Removes a destroyed anchor from every online player's currently held scepter and
     * invalidates its lightweight client metadata.
     *
     * <p>Other scepters are cleaned lazily when they are next held and synchronized.  The item
     * sync here is important because clearing only SavedData would leave the client-side main-hand
     * whitelist stale and the supply screen would still list a disconnected endpoint.</p>
     */
    public static void sendBuilderAnchorInvalidation(MinecraftServer server, UUID anchorId) {
        for (ServerPlayer player : server.getPlayerList().getPlayers()) {
            var scepter = player.getMainHandItem();
            if (!scepter.is(ModItems.REALMWRIGHT_SCEPTER.get())
                    || !AnchorBindings.unbind(scepter, anchorId)) continue;

            player.getInventory().setChanged();
            player.containerMenu.broadcastChanges();
            if (player.inventoryMenu != player.containerMenu) {
                player.inventoryMenu.broadcastChanges();
            }
            sendBuilderSnapshot(player);
        }
    }
}
