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

import net.minecraft.world.level.levelgen.Heightmap;
import javax.annotation.Nullable;
import java.util.Random;
import net.minecraft.core.Vec3i;
import net.minecraft.world.entity.Entity;
import net.minecraft.core.BlockPos;
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 speed;
    
    public MoveToSkySeeingSpot(final float float1) {
        super(ImmutableMap.<MemoryModuleType<WalkTarget>, MemoryStatus>of(MemoryModuleType.WALK_TARGET, MemoryStatus.VALUE_ABSENT));
        this.speed = float1;
    }
    
    @Override
    protected void start(final ServerLevel xd, final LivingEntity akz, final long long3) {
        final Optional<Vec3> optional6 = Optional.<Vec3>ofNullable(this.getOutdoorPosition(xd, akz));
        if (optional6.isPresent()) {
            akz.getBrain().<WalkTarget>setMemory(MemoryModuleType.WALK_TARGET, optional6.<WalkTarget>map(cvl -> new WalkTarget(cvl, this.speed, 0)));
        }
    }
    
    @Override
    protected boolean checkExtraStartConditions(final ServerLevel xd, final LivingEntity akz) {
        return !xd.canSeeSky(new BlockPos(akz));
    }
    
    @Nullable
    private Vec3 getOutdoorPosition(final ServerLevel xd, final LivingEntity akz) {
        final Random random4 = akz.getRandom();
        final BlockPos fk5 = new BlockPos(akz);
        for (int integer6 = 0; integer6 < 10; ++integer6) {
            final BlockPos fk6 = fk5.offset(random4.nextInt(20) - 10, random4.nextInt(6) - 3, random4.nextInt(20) - 10);
            if (hasNoBlocksAbove(xd, akz, fk6)) {
                return new Vec3(fk6);
            }
        }
        return null;
    }
    
    public static boolean hasNoBlocksAbove(final ServerLevel xd, final LivingEntity akz, final BlockPos fk) {
        return xd.canSeeSky(fk) && xd.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, fk).getY() <= akz.getY();
    }
}
