package net.minecraft.network.protocol.game;

import net.minecraft.network.PacketListener;
import javax.annotation.Nullable;
import net.minecraft.world.level.Level;
import java.io.IOException;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.entity.Entity;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.network.protocol.Packet;

public class ClientboundPlayerLookAtPacket implements Packet<ClientGamePacketListener> {
    private double x;
    private double y;
    private double z;
    private int entity;
    private EntityAnchorArgument.Anchor fromAnchor;
    private EntityAnchorArgument.Anchor toAnchor;
    private boolean atEntity;
    
    public ClientboundPlayerLookAtPacket() {
    }
    
    public ClientboundPlayerLookAtPacket(final EntityAnchorArgument.Anchor a, final double double2, final double double3, final double double4) {
        this.fromAnchor = a;
        this.x = double2;
        this.y = double3;
        this.z = double4;
    }
    
    public ClientboundPlayerLookAtPacket(final EntityAnchorArgument.Anchor a1, final Entity akq, final EntityAnchorArgument.Anchor a3) {
        this.fromAnchor = a1;
        this.entity = akq.getId();
        this.toAnchor = a3;
        final Vec3 cvl5 = a3.apply(akq);
        this.x = cvl5.x;
        this.y = cvl5.y;
        this.z = cvl5.z;
        this.atEntity = true;
    }
    
    @Override
    public void read(final FriendlyByteBuf kv) throws IOException {
        this.fromAnchor = kv.<EntityAnchorArgument.Anchor>readEnum(EntityAnchorArgument.Anchor.class);
        this.x = kv.readDouble();
        this.y = kv.readDouble();
        this.z = kv.readDouble();
        if (kv.readBoolean()) {
            this.atEntity = true;
            this.entity = kv.readVarInt();
            this.toAnchor = kv.<EntityAnchorArgument.Anchor>readEnum(EntityAnchorArgument.Anchor.class);
        }
    }
    
    @Override
    public void write(final FriendlyByteBuf kv) throws IOException {
        kv.writeEnum(this.fromAnchor);
        kv.writeDouble(this.x);
        kv.writeDouble(this.y);
        kv.writeDouble(this.z);
        kv.writeBoolean(this.atEntity);
        if (this.atEntity) {
            kv.writeVarInt(this.entity);
            kv.writeEnum(this.toAnchor);
        }
    }
    
    @Override
    public void handle(final ClientGamePacketListener lw) {
        lw.handleLookAt(this);
    }
    
    public EntityAnchorArgument.Anchor getFromAnchor() {
        return this.fromAnchor;
    }
    
    @Nullable
    public Vec3 getPosition(final Level bjw) {
        if (!this.atEntity) {
            return new Vec3(this.x, this.y, this.z);
        }
        final Entity akq3 = bjw.getEntity(this.entity);
        if (akq3 == null) {
            return new Vec3(this.x, this.y, this.z);
        }
        return this.toAnchor.apply(akq3);
    }
}
