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;
import java.util.stream.Stream;

public class NearestEnemiesSelector implements TargetSelector {
    private final double radius;
    private int limit = 0;
    // 是否让玩家免疫（不作为目标）
    private boolean playerImmune = false;

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

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

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

    @Override
    public List<Entity> selectTargets(Player caster) {
        Stream<Entity> stream = 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

        if (playerImmune) {
            stream = stream.filter(e -> !(e instanceof Player)); // 玩家免疫
        }

        stream = stream.sorted(Comparator.comparingDouble(e -> e.getLocation().distanceSquared(caster.getLocation())));

        if (limit > 0) {
            stream = stream.limit(limit);
        }
        return stream.collect(Collectors.toList());
    }
}
