package com.bitnix.dirtguilds.listener;

import com.bitnix.dirtguilds.DirtGuildsPlugin;
import com.bitnix.dirtguilds.guild.Guild;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;

public class GuildFriendlyFireListener implements Listener {

    private final DirtGuildsPlugin plugin;

    public GuildFriendlyFireListener(DirtGuildsPlugin plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onDamage(EntityDamageByEntityEvent event) {
        Player attacker = getPlayer(event.getDamager());
        Player victim = getPlayer(event.getEntity());

        if (attacker == null || victim == null) {
            return;
        }

        Guild attackerGuild = plugin.getGuildManager().getGuildByPlayer(attacker.getUniqueId());
        Guild victimGuild = plugin.getGuildManager().getGuildByPlayer(victim.getUniqueId());

        if (attackerGuild == null || victimGuild == null) {
            return;
        }

        if (!attackerGuild.getId().equals(victimGuild.getId())) {
            return;
        }

        if (!attackerGuild.isFriendlyFire()) {
            event.setCancelled(true);
        }
    }

    private Player getPlayer(Entity entity) {
        if (entity instanceof Player player) {
            return player;
        }
        return null;
    }
}
