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

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

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

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;

public final class OnlinePlayerManager implements Listener {
	
	private static OnlinePlayerManager instance;
	
	/**
	 * Retourne l'unique instance de la classe. Si elle n'existe pas, on tente de créer
	 * @return L'unique instance de la classe
	 */
	
	public synchronized static OnlinePlayerManager getInstance() {
		if (instance == null)
			loadNewInstance();
		return instance;
	}
	
	public synchronized static void loadNewInstance() {
		instance = new OnlinePlayerManager();
	}
	
	
	
	
	Map<Player, OnlinePlayer> players = Collections.synchronizedMap(new HashMap<Player, OnlinePlayer>());
	
	private OnlinePlayerManager() {
		
		// en cas de /reload : on ajoute les joueurs déjà en ligne
		for (Player p : PandacraftUtils.getInstance().getServer().getOnlinePlayers())
			players.put(p, new OnlinePlayer(p));
		
		
		PandacraftUtils.getInstance().getServer().getPluginManager().registerEvents(this, PandacraftUtils.getInstance());
        
	}
	
	
	
	
	
	// ----------------------------------------
	// -------------- Evènements --------------
	// ----------------------------------------
	@EventHandler
	public void onPlayerJoin (PlayerJoinEvent event)
	{
		players.put(event.getPlayer(), new OnlinePlayer(event.getPlayer()));
	}

	@EventHandler
	public void onPlayerQuit (PlayerQuitEvent event)
	{
		players.remove(event.getPlayer());
	}
	
	
	
	
	
	
	
	
	
	
	
	public static OnlinePlayer get(Player p) {
		return getInstance().players.get(p);
	}
	
	public static Collection<OnlinePlayer> getAll() {
		return new ArrayList<OnlinePlayer>(getInstance().players.values());
	}
	
	
	public static boolean isOnline(Player p) {
		return getInstance().players.containsKey(p);
	}
	
	public static Collection<OnlinePlayer> getAllNotVanished() {
		Collection<OnlinePlayer> players = getAll();
		
		for (OnlinePlayer op : players.toArray(new OnlinePlayer[players.size()])) {
			if (op.isVanished())
				players.remove(op);
		}
		
		return players;
	}
	
}
