package com.yaohun.demonskills.target;

import com.yaohun.demonskills.api.TargetSelector;
import me.Demon.DemonTeam.DTeamAPI;
import me.Demon.DemonTeam.TeamData;
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.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class TeamPlayerSelector implements TargetSelector {
    private final double radius;
    private final int limit;
    private final boolean teamBuff;

    // 默认构造：1个目标，团队增益开启
    public TeamPlayerSelector(double radius) {
        this(radius, 1, true);
    }

    // 指定数量，默认团队增益开启
    public TeamPlayerSelector(double radius, int limit) {
        this(radius, limit, true);
    }

    // 全参构造
    public TeamPlayerSelector(double radius, int limit, boolean teamBuff) {
        this.radius = radius;
        this.limit = Math.max(0, limit); // 限制不能为负数
        this.teamBuff = teamBuff;
    }

    @Override
    public List<Entity> selectTargets(Player caster) {
        TeamData teamData = DTeamAPI.getPlayerTeam(caster.getName());

        List<Entity> result = new ArrayList<>();
        // 无队伍：teamBuff = true → 空，teamBuff = false → 所有生物
        if (teamData == null) {
            if (!teamBuff) {
                for (Entity entity : caster.getNearbyEntities(radius, radius, radius)) {
                    if(entity instanceof ArmorStand) {
                        continue;
                    }
                    if(CitizensAPI.getNPCRegistry().isNPC(entity)){
                        continue;
                    }
                    if (entity instanceof LivingEntity && !entity.equals(caster)) {
                        result.add(entity);
                        if (limit > 0 && result.size() >= limit) break;
                    }
                }
            }
            return result;
        }
        // 有队伍 → 根据 teamBuff 决定筛选规则
        List<String> members = teamData.getMemberList();
        for (Entity entity : caster.getNearbyEntities(radius, radius, radius)) {
            if(entity instanceof ArmorStand) {
                continue;
            }
            if(CitizensAPI.getNPCRegistry().isNPC(entity)){
                continue;
            }
            if (limit > 0 && result.size() >= limit) break;
            if (entity.equals(caster)) continue;
            if (entity instanceof Player) {
                Player player = (Player) entity;
                boolean isTeammate = members.contains(player.getName());
                if (teamBuff && isTeammate) {
                    result.add(player);
                } else if (!teamBuff && !isTeammate) {
                    result.add(player);
                }
            } else {
                if (!teamBuff) {
                    result.add(entity);
                }
            }
        }
        return result;
    }
}