package moe.oko.opennaw.util;

import io.papermc.paper.event.player.AsyncChatEvent;
import moe.oko.opennaw.OpenNAW;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;

public class ChatHandler implements Listener {

    @EventHandler(priority = EventPriority.HIGHEST)
    public void onChat(AsyncChatEvent e) {
        var legacyComponentSerializer = LegacyComponentSerializer.builder().character('&').hexColors().build();
        var player = e.getPlayer();
        Audience audience;

        var nationString = "[" + ChatColor.valueOf(OpenNAW.getInstance().getNationHandler().getNationByPlayer(player.getUniqueId()).getColour()) + "&r] ";
        var prefix = legacyComponentSerializer.deserialize(nationString);
        var message = e.message();

        e.setCancelled(true);

        audience = Audience.audience(Bukkit.getOnlinePlayers());

        audience.sendMessage(prefix
                .append(player.displayName().color(TextColor.fromHexString("#939597")))
                .append(Component.text(": "))
                .append(message));
    }

}
