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 aom, final EntityAnchorArgument.Anchor a3) {
        this.fromAnchor = a1;
        this.entity = aom.getId();
        this.toAnchor = a3;
        final Vec3 dem5 = a3.apply(aom);
        this.x = dem5.x;
        this.y = dem5.y;
        this.z = dem5.z;
        this.atEntity = true;
    }
    
    @Override
    public void read(final FriendlyByteBuf mg) throws IOException {
        this.fromAnchor = mg.<EntityAnchorArgument.Anchor>readEnum(EntityAnchorArgument.Anchor.class);
        this.x = mg.readDouble();
        this.y = mg.readDouble();
        this.z = mg.readDouble();
        if (mg.readBoolean()) {
            this.atEntity = true;
            this.entity = mg.readVarInt();
            this.toAnchor = mg.<EntityAnchorArgument.Anchor>readEnum(EntityAnchorArgument.Anchor.class);
        }
    }
    
    @Override
    public void write(final FriendlyByteBuf mg) throws IOException {
        mg.writeEnum(this.fromAnchor);
        mg.writeDouble(this.x);
        mg.writeDouble(this.y);
        mg.writeDouble(this.z);
        mg.writeBoolean(this.atEntity);
        if (this.atEntity) {
            mg.writeVarInt(this.entity);
            mg.writeEnum(this.toAnchor);
        }
    }
    
    @Override
    public void handle(final ClientGamePacketListener nl) {
        nl.handleLookAt(this);
    }
    
    public EntityAnchorArgument.Anchor getFromAnchor() {
        return this.fromAnchor;
    }
    
    @Nullable
    public Vec3 getPosition(final Level bqb) {
        if (!this.atEntity) {
            return new Vec3(this.x, this.y, this.z);
        }
        final Entity aom3 = bqb.getEntity(this.entity);
        if (aom3 == null) {
            return new Vec3(this.x, this.y, this.z);
        }
        return this.toAnchor.apply(aom3);
    }
}
