package net.mc_pandacraft.java.plugin.pandacraftutils.simple_commands.list;

import java.util.ArrayList;

import net.mc_pandacraft.java.plugin.pandacraftutils.PandacraftUtils;
import net.mc_pandacraft.java.plugin.pandacraftutils.afk.AfkPlayer;
import net.mc_pandacraft.java.util.TimeUtil;

import org.bukkit.GameMode;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.v1_7_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;

public class CommandList implements CommandExecutor {
	private PandacraftUtils plugin;

	public CommandList(PandacraftUtils pl)
	{
		plugin = pl;
		plugin.getCommand("list").setExecutor(this);
	}

	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
	{
		boolean execute = false;
		boolean details = false;
		if(sender instanceof Player)
		{
	        if (((Player)sender).hasPermission("pandacraft.players"))
	        	execute = true;
	        if (((Player)sender).hasPermission("pandacraft.players.details"))
	        	details = true;
	    }
		else
		{
	        execute = true;
        	details = true;
		}
		
		if (execute)
		{
			Server s = plugin.getServer();
			Player[] pls = plugin.getServer().getOnlinePlayers();
			
			

			String decoration_color = "§6";
			String header = "";
			if (details && args.length > 0)
			{
				String arg = args[0].toLowerCase();
				if (arg.equals("loc") || arg.equals("world"))
					header = "Localisation des joueurs";
				else if (arg.equals("uuid"))
					header = "Identifiants des joueurs";
				else if (arg.equals("ip") || arg.equals("ping"))
					header = "IP et ping des joueurs";
				else if (arg.equals("afk"))
					header = "Status AFK des joueurs";
				else if (arg.equals("gm") || arg.equals("gamemode"))
					header = "Mode de jeu des joueurs";
				else if (arg.equals("spam"))
					header = "Niveau de spam des joueurs";
			}
			else
			{
				header = "Liste des joueurs";
			}
			
			header = header.concat(" (§7"+pls.length+decoration_color+"/§7"+s.getMaxPlayers()+decoration_color+")");
			char decoration_motif = '-';
			
			ArrayList<String> aff_list = new ArrayList<String>();
			
			if (details && args.length > 0 && (args[0].toLowerCase().equals("loc") || args[0].toLowerCase().equals("world")))
			{
				
				for (World w : plugin.getServer().getWorlds())
				{
					if (w.getPlayers().size() == 0)
						continue;
					
					
					// filtrage pour éviter d'afficher un monde vide (qui contiennent que des joueurs hors ligne)
					boolean can_continue = false;
					for (Player p : w.getPlayers())
						if (p != null && p.isOnline())
						{
							can_continue = true;
							break;
						}
					if (!can_continue)
						continue;
					// ---------
					
					
					
					aff_list.add(decoration_color+"Monde §7"+w.getName());
					
					for (Player p : w.getPlayers())
					{
						// filtrage pour éviter d'afficher des joueurs hors ligne
						if (p == null || !p.isOnline())
							continue;
						int x = p.getLocation().getBlockX();
						int y = p.getLocation().getBlockY();
						int z = p.getLocation().getBlockZ();
						String name = p.getDisplayName();
						aff_list.add(decoration_color+"- §f"+name+"§r - §7x="+x+" ; y="+y+" ; z="+z);
					}
					
				}
				
			}
			else if (details && args.length > 0)
			{
				for (Player p : pls)
				{
					if (p == null)
						continue;
					
					
					
					
					
					String name = p.getDisplayName();
					
					if (args.length > 0 && args[0].toLowerCase().equals("uuid"))
					{
						String uuid = p.getUniqueId().toString();
						
						aff_list.add("§f"+name+"§r - §7"+uuid);
					}
					else if (args.length > 0 && (args[0].toLowerCase().equals("ip") || args[0].toLowerCase().equals("ping")))
					{
						String ip = p.getAddress().getAddress().getHostAddress();
						
						int ping = ((CraftPlayer)p).getHandle().ping;
						
						aff_list.add("§f"+name+"§r - §7"+ip+"§r - ping : §7"+ping);
					}
					else if (args.length > 0 && (args[0].toLowerCase().equals("spam")))
					{
						try
						{
							int vl = plugin.chatAnalysisManager.getCAPlayer(p).getVL();
							int max_vl = plugin.chatAnalysisManager.getCAPlayer(p).getMaxVL();
							aff_list.add("§f"+name+"§r - §7"+vl+"/"+max_vl);
							
						}
						catch (NullPointerException e)
						{
							aff_list.add("§cImpossible de récupérer le niveau de spam du joueur.");
						}
					}
					else if (args.length > 0 && args[0].toLowerCase().equals("afk"))
					{
						AfkPlayer ap = plugin.commandAfk.getAfkPlayer(p);
						boolean afk = (ap != null && ap.isAfk());
						double afk_time = (ap != null)?ap.getDurationSinceLastAction():-1;
						String afkTime;
						if (afk_time > 20)
							afkTime = TimeUtil.durationToString((long)(afk_time*1000));
						else
							afkTime = "Actif";
						
						aff_list.add("§f"+name+""+((afk)?" §c[Afk]§r":"")+" §7"+afkTime+"§r");
					}
					else if (args.length > 0 && (args[0].toLowerCase().equals("gm") || args[0].toLowerCase().equals("gamemode")))
					{
						String world = p.getWorld().getName();
						double health = Math.rint(p.getHealth()*100)/100;
						double eat = Math.rint(p.getFoodLevel()*100)/100;
						boolean flyMode = p.getAllowFlight();
						String gm = (p.getGameMode() == GameMode.SURVIVAL)?("§CSurvie§r;vie:§7"+health+"§r;faim:§7"+eat+"§r"+((flyMode)?";§7canFly":""))
								:(p.getGameMode() == GameMode.CREATIVE)?"§bCréa§r"
								:(p.getGameMode() == GameMode.ADVENTURE)?("§8Aventure§r;vie:§7"+health+"§r;faim:§7"+eat+"§r"+((flyMode)?";§7canFly":""))
								:"§oInconnu";
						String afk = (plugin.commandAfk.getAfkPlayer(p) != null && plugin.commandAfk.getAfkPlayer(p).isAfk())?" §c(Afk)§r":"";
						aff_list.add("§f"+name+"§r"+afk+" - §7"+world+"§r - "+gm);
					}
					else
					{
						return false;
					}
					
				}
			}
			else
			{
				String joueurs = "";
				boolean first = true;
				for (Player p : pls)
				{
					if (p == null)
						continue;
					if (!first)
						joueurs = joueurs.concat("§r, ");
					else
						first = false;
					
					joueurs = joueurs.concat(p.getDisplayName());
					
					
				}
				
				if (pls.length > 0)
				{
					aff_list.add(joueurs);
				}
				else
					aff_list.add("Aucun joueur connecté");
				
			}
			
			
			int max_length = (header.length()-2*char_count(header, '§')) + 2;
			max_length += 2; // évite le décalage de l'entête si il n'y a aucun trait à gauche
			for (String line : aff_list)
				max_length = (line != null && (line.length()-2*char_count(line, '§')) > max_length) ? (line.length()-2*char_count(line, '§')) : max_length;
			
			if (max_length > 70) max_length = 70;
			
			
			long header_left_aff = Math.round(Math.floor((max_length - (header.length()-2*char_count(header, '§')) - 2)/2D));
			if (header_left_aff < 0) header_left_aff = 0;
			long header_right_aff = Math.round(Math.ceil((max_length - (header.length()-2*char_count(header, '§')) - 2)/2D));
			if (header_right_aff < 0) header_right_aff = 0;
			
			String final_header = decoration_color;
			String final_footer = decoration_color;
			
			for (int j=0; j<header_left_aff; j++)
				final_header = final_header + decoration_motif;
			final_header = final_header + " " + header + " ";
			for (int j=0; j<header_right_aff; j++)
				final_header = final_header + decoration_motif;

			for (int j=0; j<max_length; j++)
				final_footer = final_footer + decoration_motif;
			
			sender.sendMessage(final_header);
			for (String line : aff_list)
				sender.sendMessage(line);
			sender.sendMessage(final_footer);
			
		}
		else
			sender.sendMessage("Vous n'avez pas la permission pour cette commande.");
		
		
		
		return true;
	}
	
	
	
	
	
	
	private int char_count(String s, char c_match)
	{
		char[] chars = s.toCharArray();
		int count = 0;
		for (char c : chars)
			if (c == c_match)
				count++;
		return count;
	}
	
	
	
	
	
	
	
	
	

}
