package com.yaohun.demonskills.target;

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

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

public class ConeEnemiesSelector implements TargetSelector {
    private final double radius; // 范围
    private final double angle; // 角度（如 60°）
    private int limit = -1;
    private boolean playerImmune = false;

    public ConeEnemiesSelector(double radius, double angle) {
        this.radius = radius;
        this.angle = angle;
    }

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

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

    @Override
    public List<Entity> selectTargets(Player caster) {
        List<Entity> entityList = new ArrayList<>();
        Vector forward = caster.getLocation().getDirection().setY(0).normalize(); // 只考虑水平朝向
        Location eyeLoc = caster.getEyeLocation();
        Vector eyeVec = eyeLoc.toVector();
        for (Entity entity : caster.getNearbyEntities(radius, 3, radius)) {
            if (!(entity instanceof LivingEntity) || entity.equals(caster)) continue;
            if (entity instanceof ArmorStand) continue;
            if (CitizensAPI.getNPCRegistry().isNPC(entity)) continue;
            if(playerImmune){
                if(entity instanceof Player){
                    continue;
                }
            }

            Vector toTarget = entity.getLocation().toVector().subtract(eyeVec);
            toTarget.setY(0);

            if (toTarget.length() > radius) continue;
            toTarget.normalize();

            double angleBetween = Math.toDegrees(Math.acos(forward.dot(toTarget)));
            if (angleBetween <= angle / 2.0) {
                entityList.add(entity);
            }
        }
        /*List<String> strings = new ArrayList<>();
        for (Entity entity : entityList) {
            strings.add(entity.getType().name());
        }
        System.out.println("# "+String.join(", ", strings));*/
        return entityList;
    }

}
