package com.r3944realms.leashedplayer.network.client;

import com.r3944realms.leashedplayer.LeashedPlayer;
import com.r3944realms.leashedplayer.modInterface.IEntityLeadExtension;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import org.jetbrains.annotations.NotNull;

import java.util.UUID;

public record SyncLeashRopeLength(String entityUUID, float length) implements CustomPacketPayload {
    public static final Type<SyncLeashRopeLength> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(LeashedPlayer.MOD_ID,"sync_leash_rope_length"));
    public static final StreamCodec<FriendlyByteBuf, SyncLeashRopeLength> STREAM_CODEC =
            StreamCodec.composite(
                    ByteBufCodecs.STRING_UTF8, SyncLeashRopeLength::entityUUID,
                    ByteBufCodecs.FLOAT, SyncLeashRopeLength::length,
                    SyncLeashRopeLength::new
            );
    public void handle(IPayloadContext context) {
        context.enqueueWork(() -> {
            Entity entity = context.player().level().getEntity(UUID.fromString(entityUUID));
            if (entity instanceof IEntityLeadExtension entityLeadExtension) {
                entityLeadExtension.setLeashLength(length);
            }
        });
    }

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