package net.minecraft.world.entity.ai.behavior;

import net.minecraft.world.level.levelgen.Heightmap;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPos;
import java.util.Random;
import net.minecraft.core.Vec3i;
import net.minecraft.world.phys.Vec3;
import java.util.Optional;
import net.minecraft.server.level.ServerLevel;
import java.util.Map;
import net.minecraft.world.entity.ai.memory.WalkTarget;
import com.google.common.collect.ImmutableMap;
import net.minecraft.world.entity.ai.memory.MemoryStatus;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.LivingEntity;

public class MoveToSkySeeingSpot extends Behavior<LivingEntity> {
    private final float speedModifier;
    
    public MoveToSkySeeingSpot(final float float1) {
        super(ImmutableMap.<MemoryModuleType<WalkTarget>, MemoryStatus>of(MemoryModuleType.WALK_TARGET, MemoryStatus.VALUE_ABSENT));
        this.speedModifier = float1;
    }
    
    @Override
    protected void start(final ServerLevel zd, final LivingEntity aoy, final long long3) {
        final Optional<Vec3> optional6 = Optional.<Vec3>ofNullable(this.getOutdoorPosition(zd, aoy));
        if (optional6.isPresent()) {
            aoy.getBrain().<WalkTarget>setMemory(MemoryModuleType.WALK_TARGET, optional6.map(dem -> new WalkTarget(dem, this.speedModifier, 0)));
        }
    }
    
    @Override
    protected boolean checkExtraStartConditions(final ServerLevel zd, final LivingEntity aoy) {
        return !zd.canSeeSky(aoy.blockPosition());
    }
    
    @Nullable
    private Vec3 getOutdoorPosition(final ServerLevel zd, final LivingEntity aoy) {
        final Random random4 = aoy.getRandom();
        final BlockPos fu5 = aoy.blockPosition();
        for (int integer6 = 0; integer6 < 10; ++integer6) {
            final BlockPos fu6 = fu5.offset(random4.nextInt(20) - 10, random4.nextInt(6) - 3, random4.nextInt(20) - 10);
            if (hasNoBlocksAbove(zd, aoy, fu6)) {
                return Vec3.atBottomCenterOf(fu6);
            }
        }
        return null;
    }
    
    public static boolean hasNoBlocksAbove(final ServerLevel zd, final LivingEntity aoy, final BlockPos fu) {
        return zd.canSeeSky(fu) && zd.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, fu).getY() <= aoy.getY();
    }
}
