package com.bitnix.dirtguilds.listener;

import com.bitnix.dirtguilds.DirtGuildsPlugin;
import com.bitnix.dirtguilds.guild.Guild;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;

public class ChatListener implements Listener {

    private final DirtGuildsPlugin plugin;

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

    @EventHandler
    public void onChat(AsyncChatEvent event) {
        Player player = event.getPlayer();

        if (!plugin.getGuildManager().isGuildChatEnabled(player.getUniqueId())) {
            return;
        }

        Guild guild = plugin.getGuildManager().getGuildByPlayer(player.getUniqueId());
        if (guild == null) {
            plugin.getGuildManager().setGuildChatEnabled(player.getUniqueId(), false);
            return;
        }

        event.setCancelled(true);

        Component message = event.message();
        Component format = plugin.getMessageUtil().parse(
                "<gray>[<gold>Guild</gold>]</gray> <yellow>" + guild.getPrefix() + "</yellow> <white>" + player.getName() + "</white><gray>:</gray> "
        );

        for (Player online : Bukkit.getOnlinePlayers()) {
            Guild targetGuild = plugin.getGuildManager().getGuildByPlayer(online.getUniqueId());
            if (targetGuild != null && targetGuild.getId().equals(guild.getId())) {
                online.sendMessage(format.append(message));
            }
        }
    }
}
