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

import java.util.List;
import java.util.Map;

import net.mc_pandacraft.java.plugin.pandacraftutils.ConfigManager;
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.PlayerCommandPreprocessEvent;

public class CommandAliasManager implements Listener {
	private PandacraftUtils plugin = PandacraftUtils.getInstance();
	
	
	public CommandAliasManager() {
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
		
		
		
	}

	@EventHandler(priority=EventPriority.HIGHEST)
	public void onPlayerCommandPreprocess (PlayerCommandPreprocessEvent event)
	{
		Player p = event.getPlayer();
		
		List<Map<String, String>> aliases = ConfigManager.getInstance().CommandAlias_alias;
		for (Map<String, String> alias : aliases) {
			if (alias == null)
				continue;
			String perms = alias.get("permissions");
			String initialCmd = alias.get("initialCommand");
			String aliasCmd = alias.get("replaceWith");
			if (perms == null || initialCmd == null || aliasCmd == null)
				continue;
			
			if (!perms.equals("*")) {
				String[] aPerms = perms.split(";");
				boolean found = false;
				for (String perm : aPerms) {
					if (perm == null || perm.equals("")) continue; // boucle qui parcours les permissions de l'alias
					if (p.hasPermission(perm)) found = true;
				}
				if (!found) continue; // boucle qui parcours les alias de commandes
			}

			String mess = event.getMessage();
			
			if(mess.toLowerCase().startsWith(initialCmd))
				mess = mess.replaceFirst("(?i)"+initialCmd, aliasCmd);
			else
				continue;
			
			event.setMessage(mess);
			return;
		}
		
	}
	
	
	
}
