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

import net.fabricmc.fabric.api.networking.v1.FabricPacket;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.PacketType;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
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 class FabricClientDataPacket implements FabricPacket {
    /**
     * The constant CLIENT_TEST_DATA.
     */
    public static final ResourceLocation CLIENT_TEST_DATA =
            Lib39.rl("client_test_data");
    /**
     * The constant TYPE.
     */
    public static final PacketType<FabricClientDataPacket> TYPE = PacketType.create(
            CLIENT_TEST_DATA,
            FabricClientDataPacket::new
    );
    private final AbstractedTestSyncData clientData;
    private final int targetEntityId;

    /**
     * Instantiates a new Client data packet.
     *
     * @param clientData     the client data
     * @param targetEntityId the target entity id
     */
    public FabricClientDataPacket(AbstractedTestSyncData clientData, int targetEntityId) {
        this.clientData = clientData;
        this.targetEntityId = targetEntityId;
    }

    /**
     * Instantiates a new Client data packet.
     *
     * @param buf the buf
     */
    public FabricClientDataPacket(FriendlyByteBuf buf) {
        this.clientData = FabricTestSyncData.staticFromBytes(buf);
        this.targetEntityId = buf.readInt();
    }


    @Override
    public void write(FriendlyByteBuf buf) {
        clientData.toBytes(buf);
        buf.writeInt(targetEntityId);
    }

    @Override
    public PacketType<?> getType() {
        return TYPE;
    }

    /**
     * Receive.
     *
     * @param packet       the packet
     * @param serverPlayer the server player
     * @param packetSender the packet sender
     */
    public static void receive(@NotNull FabricClientDataPacket packet, @NotNull ServerPlayer serverPlayer, PacketSender packetSender) {
        FabricFabricItem.handleClientDataFromPacket(serverPlayer, packet.clientData, packet.targetEntityId);
    }
}