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

import net.minecraft.core.BlockPos;
import net.minecraft.tags.TagKey;
import net.minecraft.util.Continuation;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.ai.memory.WalkTarget;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import org.apache.commons.lang3.mutable.MutableLong;
import org.apache.commons.lang3.mutable.MutableObject;

public class TryFindLiquid {
	public static BehaviorControl<PathfinderMob> create(final int range, final float speedModifier, final TagKey<Fluid> fluidTag) {
		MutableLong nextOkStartTime = new MutableLong(0L);
		return BehaviorBuilder.create(
			i -> i.group(i.absent(MemoryModuleType.ATTACK_TARGET), i.absent(MemoryModuleType.WALK_TARGET), i.registered(MemoryModuleType.LOOK_TARGET))
				.apply(
					i,
					(var4x, walkTarget, lookTarget) -> (level, body, timestamp) -> {
						if (level.getFluidState(body.blockPosition()).is(fluidTag)) {
							return false;
						}

						if (timestamp < nextOkStartTime.longValue()) {
							nextOkStartTime.setValue(timestamp + 20L + 2L);
							return true;
						}

						MutableObject<BlockPos> foundPos = new MutableObject<>(null);
						BlockPos bodyBlockPos = body.blockPosition();
						level.findBlocksInBoxByManhattanDistance(bodyBlockPos, range)
							.filterPos(pos -> pos.differsHorizontally(bodyBlockPos))
							.filterState(state -> state.getBlock() instanceof LiquidBlock && state.getFluidState().is(fluidTag))
							.forEachUntil((pos, var4xx) -> {
								BlockState aboveState = level.getBlockState(pos.above());
								if (aboveState.isAir()) {
									foundPos.setValue(pos.immutable());
									return Continuation.ABORT;
								}

								if (foundPos.get() == null && !pos.closerToCenterThan(body.position(), 1.5)) {
									foundPos.setValue(pos.immutable());
								}

								return Continuation.CONTINUE;
							});
						BlockPos blockPos = foundPos.get();
						if (blockPos != null) {
							lookTarget.set(new BlockPosTracker(blockPos));
							walkTarget.set(new WalkTarget(new BlockPosTracker(blockPos), speedModifier, 0));
						}

						nextOkStartTime.setValue(timestamp + 40L);
						return true;
					}
				)
		);
	}
}
