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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import de.luricos.bukkit.xAuth.events.xAuthLoginEvent;

public class LoginLogoutManager implements Listener {

	private PandacraftUtils plugin;
	
	private List<Player> loggedInPlayer = new ArrayList<Player>();
	
	
	public LoginLogoutManager(PandacraftUtils pl) {
		plugin = pl;
		
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}
	
	
	@EventHandler
	public void onPlayerJoin(PlayerJoinEvent event) {
		event.setJoinMessage(null);
	}
	
	
	@EventHandler
	public void onxAuthLogin(xAuthLoginEvent event) {
		loggedInPlayer.add(event.getPlayer());
		
		if (EssentialsInterface.isPlayerVanished(event.getPlayer())) return;
		
		plugin.getServer().broadcastMessage(ChatColor.YELLOW+event.getPlayer().getDisplayName()+ChatColor.YELLOW+" vient de se connecter");
	}
	
	@EventHandler
	public void onPlayerQuit(PlayerQuitEvent event) {
		event.setQuitMessage(null);
		
		if (!isPlayerLoggedIn(event.getPlayer()))
			return;
		
		loggedInPlayer.remove(event.getPlayer());
		
		// on affiche le message que si le joueur n'est pas vanish
		if (EssentialsInterface.isPlayerVanished(event.getPlayer())) return;
		
		plugin.getServer().broadcastMessage(ChatColor.YELLOW+event.getPlayer().getDisplayName()+ChatColor.YELLOW+" a quitté le jeu");
	}
	
	
	
	
	public List<Player> getLoggedInPlayers() { return loggedInPlayer; }
	
	public List<Player> getLoggedOutPlayers() {
		List<Player> players = new ArrayList<Player>(Arrays.asList(plugin.getServer().getOnlinePlayers()));
		players.removeAll(loggedInPlayer);
		return players;
	}
	
	public boolean isPlayerLoggedIn(Player p) {
		return loggedInPlayer.contains(p);
	}
	
}
