package net.mc_pandacraft.java.plugin.pandacraftutils.chat_analyzer;

import net.mc_pandacraft.java.plugin.pandacraftutils.PandacraftUtils;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

public class ChatAnalysisManager implements Listener {
	
	private ChatAnalysisPlayer[] CAPlayers;
	
	private PandacraftUtils plugin;

	public ChatAnalysisManager(PandacraftUtils pl)
	{
		plugin = pl;
		
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
		
		CAPlayers = new ChatAnalysisPlayer[plugin.getServer().getMaxPlayers()];
		

		// analyse des joueurs déjà en ligne (/reload)
		for (Player p : plugin.getServer().getOnlinePlayers())
			onPlayerJoin(new PlayerJoinEvent(p, ""));	// simule l'évènement d'arrivé d'un joueur, pour le rajouter
	}
	
	@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)
	public void onAsyncPlayerChat(AsyncPlayerChatEvent event)
	{
		try {
			getCAPlayer(event.getPlayer()).onAsyncPlayerChat(event);
		} catch (NullPointerException e) { }
	}
	
	@EventHandler(priority=EventPriority.HIGHEST)
	public void onPlayerCommandPreprocess (PlayerCommandPreprocessEvent event)
	{
		try {
			getCAPlayer(event.getPlayer()).onPlayerCommandPreprocess(event);
		} catch (NullPointerException e) { }
	}
	
	
	
	
	public ChatAnalysisPlayer getCAPlayer(Player p)
	{
		if (p == null || !p.isOnline())
			return null;
		for (ChatAnalysisPlayer ap : CAPlayers)
		{
			if (ap != null && ap.getPlayer() == p)
				return ap;
		}
		return null;
	}
	
	
	
	@EventHandler
	public void onPlayerJoin (PlayerJoinEvent event)
	{
		int i=0;
		while (i<CAPlayers.length && CAPlayers[i] != null) i++;
		if (CAPlayers[i] == null) CAPlayers[i] = new ChatAnalysisPlayer(plugin, event.getPlayer());
	}
	

	@EventHandler
	public void onPlayerQuit (PlayerQuitEvent event)
	{

		for (int i=0; i<CAPlayers.length; i++)
		{
			if (CAPlayers[i] == null)
				continue;
			if (CAPlayers[i].getPlayer() == event.getPlayer())
				CAPlayers[i] = null;
		}
	}
	
	
}
