package net.minecraft.world.item;

import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.LivingEntity;
import javax.annotation.Nullable;
import net.minecraft.world.level.Level;
import net.minecraft.resources.ResourceLocation;

public class CompassItem extends Item {
    public CompassItem(final Properties a) {
        super(a);
        this.addProperty(new ResourceLocation("angle"), new ItemPropertyFunction() {
            private double rotation;
            private double rota;
            private long lastUpdateTick;
            
            @Override
            public float call(final ItemStack ben, @Nullable Level bjw, @Nullable final LivingEntity akz) {
                if (akz == null && !ben.isFramed()) {
                    return 0.0f;
                }
                final boolean boolean5 = akz != null;
                final Entity akq6 = boolean5 ? akz : ben.getFrame();
                if (bjw == null) {
                    bjw = akq6.level;
                }
                double double11;
                if (bjw.dimension.isNaturalDimension()) {
                    double double9 = boolean5 ? akq6.yRot : this.getFrameRotation((ItemFrame)akq6);
                    double9 = Mth.positiveModulo(double9 / 360.0, 1.0);
                    final double double10 = this.getSpawnToAngle(bjw, akq6) / 6.2831854820251465;
                    double11 = 0.5 - (double9 - 0.25 - double10);
                }
                else {
                    double11 = Math.random();
                }
                if (boolean5) {
                    double11 = this.wobble(bjw, double11);
                }
                return Mth.positiveModulo((float)double11, 1.0f);
            }
            
            private double wobble(final Level bjw, final double double2) {
                if (bjw.getGameTime() != this.lastUpdateTick) {
                    this.lastUpdateTick = bjw.getGameTime();
                    double double3 = double2 - this.rotation;
                    double3 = Mth.positiveModulo(double3 + 0.5, 1.0) - 0.5;
                    this.rota += double3 * 0.1;
                    this.rota *= 0.8;
                    this.rotation = Mth.positiveModulo(this.rotation + this.rota, 1.0);
                }
                return this.rotation;
            }
            
            private double getFrameRotation(final ItemFrame avr) {
                return Mth.wrapDegrees(180 + avr.getDirection().get2DDataValue() * 90);
            }
            
            private double getSpawnToAngle(final LevelAccessor bjx, final Entity akq) {
                final BlockPos fk4 = bjx.getSharedSpawnPos();
                return Math.atan2(fk4.getZ() - akq.getZ(), fk4.getX() - akq.getX());
            }
        });
    }
}
