package net.minecraft.world.entity;

import it.unimi.dsi.fastutil.objects.ObjectArraySet;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.world.level.Level;

public interface OwnableEntity {
    @Nullable
    EntityReference<LivingEntity> getOwnerReference();

    Level level();

    @Nullable
    default LivingEntity getOwner() {
        return EntityReference.get(this.getOwnerReference(), this.level(), LivingEntity.class);
    }

    @Nullable
    default LivingEntity getRootOwner() {
        Set<Object> set = new ObjectArraySet<>();
        LivingEntity owner = this.getOwner();
        set.add(this);

        while (owner instanceof OwnableEntity) {
            OwnableEntity ownableEntity = (OwnableEntity)owner;
            LivingEntity owner1 = ownableEntity.getOwner();
            if (set.contains(owner1)) {
                return null;
            }

            set.add(owner);
            owner = ownableEntity.getOwner();
        }

        return owner;
    }
}
