package AITB_2022.module.complex;

import adf.core.agent.info.*;
import adf.core.component.module.complex.HumanDetector;
import adf.core.agent.module.ModuleManager;
import adf.core.agent.develop.DevelopData;
import rescuecore2.standard.entities.*;
import rescuecore2.worldmodel.EntityID;
import java.util.*;

public class AITHumanDetector extends HumanDetector {
    private EntityID result;

    public AITHumanDetector(
            AgentInfo ai, WorldInfo wi, ScenarioInfo si,
            ModuleManager mm, DevelopData dd) {
        super(ai, wi, si, mm, dd);
    }

    // Tactics内の2に相当
    @Override
    public EntityID getTarget() {
        return this.result;
    }

    // Tactics内の1に相当
    @Override
    public HumanDetector calc() {
        EntityID me = this.agentInfo.getID();
        Collection<EntityID> ids = this.worldInfo.getEntityIDsOfType(StandardEntityURN.CIVILIAN);

        EntityID nearestID = null;
        double nearestDistance = Double.POSITIVE_INFINITY;

        for (EntityID id : ids) {
            StandardEntity entity = this.worldInfo.getEntity(id);
            Civilian civilian = (Civilian) entity;
            boolean isAlive = civilian.isHPDefined() && civilian.getHP() > 0;
            if (!isAlive)
                continue;
            boolean isBury = civilian.isBuriednessDefined() && civilian.getBuriedness() > 0;
            if (isBury) {
                double distance = this.worldInfo.getDistance(me, id);
                if (distance < nearestDistance) {
                    nearestID = id;
                    nearestDistance = distance;
                }
            }
        }
        this.result = nearestID;
        return this;
    }
}