package com.arckenver.nations.listener;

import java.util.Optional;

import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.filter.cause.First;
import org.spongepowered.api.event.message.MessageChannelEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.serializer.TextSerializers;

import com.arckenver.nations.ConfigHandler;
import com.arckenver.nations.DataHandler;
import com.arckenver.nations.channel.NationMessageChannel;
import com.arckenver.nations.object.Nation;

public class ChatListener
{

	@Listener(order = Order.LATE)
	public void onPlayerChat(MessageChannelEvent.Chat e, @First Player p)
	{
		Nation nation = DataHandler.getNationOfPlayer(p.getUniqueId());
		if (nation == null)
		{
			return;
		}
		MessageChannel chan = MessageChannel.TO_ALL;
		Optional<MessageChannel> channel = e.getChannel();
		if (channel.isPresent())
		{
			chan = channel.get();
		}
		
		if (chan.equals(MessageChannel.TO_ALL) && ConfigHandler.getNode("others", "enableNationTag").getBoolean(true))
		{
			e.setMessage(TextSerializers.FORMATTING_CODE.deserialize(ConfigHandler.getNode("others", "publicChatFormat").getString().replaceAll("\\{NATION\\}", nation.getTag()).replaceAll("\\{TITLE\\}", DataHandler.getCitizenTitle(p.getUniqueId()))), e.getMessage());
		}
		else if (chan instanceof NationMessageChannel)
		{
			e.setMessage(Text.of(TextSerializers.FORMATTING_CODE.deserialize(ConfigHandler.getNode("others", "nationChatFormat").getString().replaceAll("\\{NATION\\}", nation.getTag()).replaceAll("\\{TITLE\\}", DataHandler.getCitizenTitle(p.getUniqueId()))), TextColors.YELLOW, e.getMessage()));
			DataHandler.getSpyChannel().send(p, Text.of(TextSerializers.FORMATTING_CODE.deserialize(ConfigHandler.getNode("others", "nationSpyChatTag").getString()), TextColors.RESET, e.getMessage()));
		}
	}
}

@@ -326,16 +326,90 @@
 lEvent;%0A
+import org.spongepowered.api.event.message.MessageEvent.MessageFormatter;%0A
 import o
@@ -1208,16 +1208,67 @@
 %0A%09%09%7D%0A%09%09%0A
+%09%09MessageFormatter formater = e.getFormatter();%0A%09%09%0A
 %09%09if (ch
@@ -1388,24 +1388,32 @@
 .setMessage(
+Text.of(
 TextSerializ
@@ -1626,28 +1626,73 @@
 d()))), 
-e.getMessage
+formater.getHeader().toText()), formater.getBody().toText
 ());%0A%09%09%7D
@@ -1999,39 +1999,92 @@
 )), 
-TextColors.YELLOW, e.getMessage
+formater.getHeader().toText()), Text.of(TextColors.YELLOW, formater.getBody().toText
 ()))

Fix chat message handling