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

import net.minecraft.world.entity.ai.Brain;
import net.minecraft.world.entity.Entity;
import java.util.List;
import net.minecraft.server.level.ServerLevel;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import net.minecraft.world.entity.ai.memory.MemoryStatus;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import java.util.function.Predicate;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;

public class SetLookAndInteract extends Behavior<LivingEntity> {
    private final EntityType<?> type;
    private final int interactionRangeSqr;
    private final Predicate<LivingEntity> targetFilter;
    private final Predicate<LivingEntity> selfFilter;
    
    public SetLookAndInteract(final EntityType<?> aoq, final int integer, final Predicate<LivingEntity> predicate3, final Predicate<LivingEntity> predicate4) {
        super(ImmutableMap.<MemoryModuleType<PositionTracker>, MemoryStatus>of(MemoryModuleType.LOOK_TARGET, MemoryStatus.REGISTERED, (MemoryModuleType<PositionTracker>)MemoryModuleType.INTERACTION_TARGET, MemoryStatus.VALUE_ABSENT, (MemoryModuleType<PositionTracker>)MemoryModuleType.VISIBLE_LIVING_ENTITIES, MemoryStatus.VALUE_PRESENT));
        this.type = aoq;
        this.interactionRangeSqr = integer * integer;
        this.targetFilter = predicate4;
        this.selfFilter = predicate3;
    }
    
    public SetLookAndInteract(final EntityType<?> aoq, final int integer) {
        this(aoq, integer, aoy -> true, aoy -> true);
    }
    
    public boolean checkExtraStartConditions(final ServerLevel zd, final LivingEntity aoy) {
        return this.selfFilter.test(aoy) && this.getVisibleEntities(aoy).stream().anyMatch(this::isMatchingTarget);
    }
    
    public void start(final ServerLevel zd, final LivingEntity aoy, final long long3) {
        super.start(zd, aoy, long3);
        final Brain<?> apr6 = aoy.getBrain();
        final Brain brain;
        apr6.<List<LivingEntity>>getMemory(MemoryModuleType.VISIBLE_LIVING_ENTITIES).ifPresent(list -> list.stream().filter(aoy2 -> aoy2.distanceToSqr(aoy) <= this.interactionRangeSqr).filter(this::isMatchingTarget).findFirst().ifPresent(aoy -> {
            brain.setMemory(MemoryModuleType.INTERACTION_TARGET, aoy);
            brain.setMemory(MemoryModuleType.LOOK_TARGET, new EntityTracker(aoy, true));
        }));
    }
    
    private boolean isMatchingTarget(final LivingEntity aoy) {
        return this.type.equals(aoy.getType()) && this.targetFilter.test(aoy);
    }
    
    private List<LivingEntity> getVisibleEntities(final LivingEntity aoy) {
        return aoy.getBrain().<List<LivingEntity>>getMemory(MemoryModuleType.VISIBLE_LIVING_ENTITIES).get();
    }
}
