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

import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.village.poi.PoiType;
import net.minecraft.server.level.ServerLevel;
import java.util.Map;
import net.minecraft.core.GlobalPos;
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.npc.VillagerProfession;
import net.minecraft.world.entity.npc.Villager;

public class PoiCompetitorScan extends Behavior<Villager> {
    final VillagerProfession profession;
    
    public PoiCompetitorScan(final VillagerProfession bds) {
        super(ImmutableMap.<MemoryModuleType<GlobalPos>, MemoryStatus>of(MemoryModuleType.JOB_SITE, MemoryStatus.VALUE_PRESENT, (MemoryModuleType<GlobalPos>)MemoryModuleType.LIVING_ENTITIES, MemoryStatus.VALUE_PRESENT));
        this.profession = bds;
    }
    
    @Override
    protected void start(final ServerLevel zd, final Villager bdp, final long long3) {
        final GlobalPos gc6 = bdp.getBrain().<GlobalPos>getMemory(MemoryModuleType.JOB_SITE).get();
        zd.getPoiManager().getType(gc6.pos()).ifPresent(ayc -> BehaviorUtils.getNearbyVillagersWithCondition(bdp, bdp -> this.competesForSameJobsite(gc6, ayc, bdp)).reduce(bdp, PoiCompetitorScan::selectWinner));
    }
    
    private static Villager selectWinner(final Villager bdp1, final Villager bdp2) {
        Villager bdp3;
        Villager bdp4;
        if (bdp1.getVillagerXp() > bdp2.getVillagerXp()) {
            bdp3 = bdp1;
            bdp4 = bdp2;
        }
        else {
            bdp3 = bdp2;
            bdp4 = bdp1;
        }
        bdp4.getBrain().<GlobalPos>eraseMemory(MemoryModuleType.JOB_SITE);
        return bdp3;
    }
    
    private boolean competesForSameJobsite(final GlobalPos gc, final PoiType ayc, final Villager bdp) {
        return this.hasJobSite(bdp) && gc.equals(bdp.getBrain().<GlobalPos>getMemory(MemoryModuleType.JOB_SITE).get()) && this.hasMatchingProfession(ayc, bdp.getVillagerData().getProfession());
    }
    
    private boolean hasMatchingProfession(final PoiType ayc, final VillagerProfession bds) {
        return bds.getJobPoiType().getPredicate().test(ayc);
    }
    
    private boolean hasJobSite(final Villager bdp) {
        return bdp.getBrain().<GlobalPos>getMemory(MemoryModuleType.JOB_SITE).isPresent();
    }
}
