package com.gamingmesh.jobs.stuff.complement;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.JobsPlayer;
import com.gamingmesh.jobs.stuff.Util;

@SuppressWarnings("deprecation")
public class JobsChatEvent implements Listener {

	private Jobs plugin;

	public JobsChatEvent(Jobs plugin) {
		this.plugin = plugin;
	}

	@EventHandler(priority = EventPriority.NORMAL)
	public void asyncPlayerChatEvent(final AsyncPlayerChatEvent event) {
		if (event.isCancelled() || Util.getJobsEditorMap().isEmpty())
			return;

		final String msg = Util.getJobsEditorMap().remove(event.getPlayer().getUniqueId());
		if (msg != null) {
			plugin.getServer().getScheduler().runTask(plugin,
					() -> event.getPlayer().performCommand(msg + event.getMessage()));
			event.setCancelled(true);
		}
	}

	// Adding to chat prefix job name
	@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
	public void onPlayerChat(AsyncPlayerChatEvent event) {
		if (!Jobs.getGCManager().getModifyChat())
			return;

		JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(event.getPlayer());
		String honorific = jPlayer != null ? jPlayer.getDisplayHonorific() : "";
		if (honorific.equals(" "))
			honorific = "";

		event.setFormat(event.getFormat().replace("%1$s", honorific + "%1$s"));
	}

	// Changing chat prefix variable to job name
	@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
	public void onPlayerChatLow(AsyncPlayerChatEvent event) {
		onPlayerChatHigh(event);
	}

	// Changing chat prefix variable to job name
	@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
	public void onPlayerChatHigh(AsyncPlayerChatEvent event) {
		if (Jobs.getGCManager().getModifyChat())
			return;

		JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(event.getPlayer());
		String honorific = jPlayer != null ? jPlayer.getDisplayHonorific() : "";
		if (honorific.equals(" "))
			honorific = "";

		event.setFormat(event.getFormat().replace("{jobs}", honorific));
	}
}

@@ -2098,39 +2098,55 @@
 orific = %22%22;%0A%0A%09%09
+String format = 
 event.
-s
+g
 etFormat(event.g
@@ -2130,39 +2130,80 @@
 event.getFormat(
+);%0A%09%09if (format.contains(%22%7Bjobs%7D%22)) %7B%0A%09%09%09
 event.
-g
+s
 etFormat().repla
@@ -2187,33 +2187,38 @@
 event.setFormat(
-)
+format
 .replace(%22%7Bjobs%7D
@@ -2233,13 +2233,17 @@
 ific));%0A
+%09%09%7D%0A
 %09%7D%0A%7D%0A

Make sure that the chat format contains jobs variable