package com.yaohun.demonskills.target;

import com.yaohun.demonskills.api.TargetSelector;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class NearestEnemiesSelector implements TargetSelector {
    private final double radius;
    private int limit = 0;

    public NearestEnemiesSelector(double radius) {
        this.radius = radius;
    }

    public NearestEnemiesSelector(double radius, int limit) {
        this.radius = radius;
        this.limit = limit;
    }

    @Override
    public List<Entity> selectTargets(Player caster) {
        if(limit != 0) {
            return caster.getNearbyEntities(radius, radius, radius).stream()
                    .filter(e -> !(e instanceof ArmorStand))
                    .filter(e -> e instanceof LivingEntity && !e.equals(caster))
                    .filter(e -> !CitizensAPI.getNPCRegistry().isNPC(e)) // 排除NPC
                    .sorted(Comparator.comparingDouble(e -> e.getLocation().distanceSquared(caster.getLocation())))
                    .limit(limit)
                    .collect(Collectors.toList());
        } else {
            return caster.getNearbyEntities(radius, radius, radius).stream()
                    .filter(e -> !(e instanceof ArmorStand))
                    .filter(e -> !CitizensAPI.getNPCRegistry().isNPC(e)) // 排除NPC
                    .filter(e -> e instanceof LivingEntity && !e.equals(caster))
                    .collect(Collectors.toList());
        }
    }
}
