package autumn_2023.module.complex;

import adf.core.agent.develop.DevelopData;
import adf.core.agent.info.AgentInfo;
import adf.core.agent.info.ScenarioInfo;
import adf.core.agent.info.WorldInfo;
import adf.core.agent.module.ModuleManager;
import adf.core.component.module.complex.HumanDetector;
import rescuecore2.standard.entities.Civilian;
import rescuecore2.standard.entities.Human;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.EntityID;

import java.util.Set;
import java.util.stream.Collectors;

public class AuctionFBHumanDetector extends HumanDetector {
    private EntityID result = null;

    public AuctionFBHumanDetector(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) {
        super(ai, wi, si, moduleManager, developData);
    }

    @Override
    public EntityID getTarget() {
        return this.result;
    }

    @Override
    public HumanDetector calc() {
        final Set<EntityID> rescueTargetInSamePosition = this.worldInfo.getChanged().getChangedEntities().parallelStream()
                .map(this.worldInfo::getEntity)
                .filter(Civilian.class::isInstance)
                .map(Civilian.class::cast)
                .filter(e -> this.agentInfo.getPosition().equals(e.getPosition()))
                .filter(Human::isHPDefined)
                .filter(e -> e.getHP() > 0)
                .filter(Human::isBuriednessDefined)
                .filter(e -> e.getBuriedness() > 0)
                .map(StandardEntity::getID)
                .collect(Collectors.toSet());

        if (rescueTargetInSamePosition.isEmpty()) {
            this.result = null;
            return this;
        }

        if (rescueTargetInSamePosition.contains(this.result)) {
            return this;
        }

        this.result = rescueTargetInSamePosition.stream().findAny().orElse(null);
        return this;
    }
}
