package com.tiedup.remake.network.sync;

import com.tiedup.remake.network.base.AbstractClientPacket;
import java.util.UUID;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Packet sent from server to client to sync leash proxy information.
 * Tells the client which proxy entity follows which player.
 *
 * This allows the client to position the proxy locally each frame,
 * rather than waiting for server position updates (much smoother).
 *
 * Uses UUID for player identification (persistent across restarts)
 * and entity ID for proxy (runtime entity only).
 */
public class PacketSyncLeashProxy extends AbstractClientPacket {

    /** The player UUID that the proxy follows (persistent) */
    private final UUID targetPlayerUUID;

    /** The proxy entity ID (runtime only, recreated on restart) */
    private final int proxyId;

    /** True = attach proxy to player, False = detach */
    private final boolean attach;

    /**
     * Create an attach packet.
     */
    public static PacketSyncLeashProxy attach(
        UUID targetPlayerUUID,
        int proxyId
    ) {
        return new PacketSyncLeashProxy(targetPlayerUUID, proxyId, true);
    }

    /**
     * Create a detach packet.
     */
    public static PacketSyncLeashProxy detach(UUID targetPlayerUUID) {
        return new PacketSyncLeashProxy(targetPlayerUUID, -1, false);
    }

    private PacketSyncLeashProxy(
        UUID targetPlayerUUID,
        int proxyId,
        boolean attach
    ) {
        this.targetPlayerUUID = targetPlayerUUID;
        this.proxyId = proxyId;
        this.attach = attach;
    }

    /**
     * Encode packet to buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeUUID(targetPlayerUUID);
        buf.writeInt(proxyId);
        buf.writeBoolean(attach);
    }

    /**
     * Decode packet from buffer.
     */
    public static PacketSyncLeashProxy decode(FriendlyByteBuf buf) {
        UUID targetPlayerUUID = buf.readUUID();
        int proxyId = buf.readInt();
        boolean attach = buf.readBoolean();
        return new PacketSyncLeashProxy(targetPlayerUUID, proxyId, attach);
    }

    @Override
    @OnlyIn(Dist.CLIENT)
    protected void handleClientImpl() {
        com.tiedup.remake.client.events.LeashProxyClientHandler.handleSyncPacket(
            targetPlayerUUID,
            proxyId,
            attach
        );
    }
}
