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

import net.minecraft.network.FriendlyByteBuf;
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 net.minecraft.world.entity.player.Player;
import net.neoforged.neoforge.network.handling.IPayloadContext;
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.TestSyncData;
import top.r3944realms.lib39.example.content.item.NeoForgeFabricItem;

/**
 * The type Client data packet.
 */
public record ClientDataPayload(AbstractedTestSyncData clientData, int targetEntityId) implements CustomPacketPayload {
    /**
     * The constant CLIENT_DATA_PACKET_ID.
     */
    public static final Identifier CLIENT_DATA_PACKET_ID =
            Lib39.rl("client_data");
    /**
     * The constant TYPE.
     */
    public static final Type<ClientDataPayload> TYPE = new Type<>(CLIENT_DATA_PACKET_ID);

    /**
     * The constant STREAM_CODEC.
     */
    public static final StreamCodec<RegistryFriendlyByteBuf, ClientDataPayload> STREAM_CODEC =
            StreamCodec.ofMember(ClientDataPayload::toBytes, ClientDataPayload::new);

    /**
     * Instantiates a new Client data packet.
     *
     * @param buf the buf
     */
    public ClientDataPayload(FriendlyByteBuf buf) {
        this(TestSyncData.staticFromBytes(buf), buf.readInt());
    }

    /**
     * To bytes.
     *
     * @param buf the buf
     */
    public void toBytes(FriendlyByteBuf buf) {
        clientData.toBytes(buf);
        buf.writeInt(targetEntityId);
    }


    /**
     * Handle.
     *
     * @param payload the payload
     * @param context the context
     */
    public static void handle(ClientDataPayload payload, @NotNull IPayloadContext context) {

        context.enqueueWork(() -> {
            Player player = context.player();
            if (player instanceof ServerPlayer serverPlayer) {
                // 处理客户端发送的数据
                handleClientData(serverPlayer, payload.clientData(), payload.targetEntityId());
            }
        });

    }

    private static void handleClientData(ServerPlayer player, AbstractedTestSyncData clientData, int targetEntityId) {
        NeoForgeFabricItem.handleClientDataFromPacket(player, clientData, targetEntityId);
    }

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