package org.twipnetwork.colorfulwords;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

public class ChatListener implements Listener {
    private final ColorfulWords plugin;

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

    @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event) {
        String colorHex = plugin.getPlayerColor(event.getPlayer().getUniqueId());
        if (colorHex == null) {
            colorHex = "#ffffff";
        }
            String playerName = event.getPlayer().getName();
            String messageContent = event.getMessage();
            TextColor color = TextColor.fromHexString(colorHex);
            var mm = MiniMessage.miniMessage();
            var recipents = event.getRecipients();
            var newmessage = mm.deserialize(
                    "<white><<" + color + ">" + playerName + "</" + color + ">></white> <" + color + ">" + messageContent + "</" + color + ">"
            );
            for (Player recipient :recipents){
                recipient.sendMessage(newmessage);
            }

            event.setCancelled(true);
    }
}
