package top.r3944realms.lib39.example.core.network;

import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerPlayer;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.example.content.data.AbstractedTestSyncData;
import top.r3944realms.lib39.example.content.data.FabricTestSyncData;
import top.r3944realms.lib39.example.content.item.FabricFabricItem;

/**
 * The type Client data packet.
 */
public record FabricClientDataPacket(AbstractedTestSyncData clientData, int targetEntityId)  implements CustomPacketPayload {
    /**
     * The constant CLIENT_TEST_DATA.
     */
    public static final Identifier CLIENT_TEST_DATA =
            Lib39.rl("client_test_data");

    /**
     * The constant TYPE.
     */
    public static final CustomPacketPayload.Type<FabricClientDataPacket> TYPE =
            new CustomPacketPayload.Type<>(CLIENT_TEST_DATA);

    /**
     * Stream codec for serializing/deserializing the packet.
     */
    public static final StreamCodec<RegistryFriendlyByteBuf, FabricClientDataPacket> STREAM_CODEC =
            StreamCodec.ofMember(FabricClientDataPacket::write, FabricClientDataPacket::new);

    /**
     * Instantiates a new Client data packet from buffer.
     *
     * @param buf the buffer
     */
    public FabricClientDataPacket(RegistryFriendlyByteBuf buf) {
        this(FabricTestSyncData.staticFromBytes(buf), buf.readInt());
    }

    /**
     * Write packet data to buffer.
     *
     * @param buf the buffer
     */
    public void write(RegistryFriendlyByteBuf buf) {
        clientData.toBytes(buf);
        buf.writeInt(targetEntityId);
    }

    @Override
    public @NotNull Type<? extends CustomPacketPayload> type() {
        return TYPE;
    }

    /**
     * Handle packet on server side.
     * Register this with ServerPlayNetworking.registerGlobalReceiver
     *
     * @param packet  the packet
     * @param context the context
     */
    public static void handle(FabricClientDataPacket packet, ServerPlayNetworking.Context context) {
        ServerPlayer serverPlayer = context.player();
        // PacketSender is no longer needed, use context.responseSender() if needed
        FabricFabricItem.handleClientDataFromPacket(serverPlayer, packet.clientData, packet.targetEntityId);
    }
}