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<?> aku, final int integer, final Predicate<LivingEntity> predicate3, final Predicate<LivingEntity> predicate4) {
        super(ImmutableMap.<MemoryModuleType<PositionWrapper>, MemoryStatus>of(MemoryModuleType.LOOK_TARGET, MemoryStatus.REGISTERED, (MemoryModuleType<PositionWrapper>)MemoryModuleType.INTERACTION_TARGET, MemoryStatus.VALUE_ABSENT, (MemoryModuleType<PositionWrapper>)MemoryModuleType.VISIBLE_LIVING_ENTITIES, MemoryStatus.VALUE_PRESENT));
        this.type = aku;
        this.interactionRangeSqr = integer * integer;
        this.targetFilter = predicate4;
        this.selfFilter = predicate3;
    }
    
    public SetLookAndInteract(final EntityType<?> aku, final int integer) {
        this(aku, integer, akz -> true, akz -> true);
    }
    
    public boolean checkExtraStartConditions(final ServerLevel xd, final LivingEntity akz) {
        return this.selfFilter.test(akz) && this.getVisibleEntities(akz).stream().anyMatch(this::isMatchingTarget);
    }
    
    public void start(final ServerLevel xd, final LivingEntity akz, final long long3) {
        super.start(xd, akz, long3);
        final Brain<?> alp6 = akz.getBrain();
        final Brain brain;
        alp6.<List<LivingEntity>>getMemory(MemoryModuleType.VISIBLE_LIVING_ENTITIES).ifPresent(list -> list.stream().filter(akz2 -> akz2.distanceToSqr(akz) <= this.interactionRangeSqr).filter(this::isMatchingTarget).findFirst().ifPresent(akz -> {
            brain.setMemory(MemoryModuleType.INTERACTION_TARGET, akz);
            brain.setMemory(MemoryModuleType.LOOK_TARGET, new EntityPosWrapper(akz));
        }));
    }
    
    private boolean isMatchingTarget(final LivingEntity akz) {
        return this.type.equals(akz.getType()) && this.targetFilter.test(akz);
    }
    
    private List<LivingEntity> getVisibleEntities(final LivingEntity akz) {
        return akz.getBrain().<List<LivingEntity>>getMemory(MemoryModuleType.VISIBLE_LIVING_ENTITIES).get();
    }
}
