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

import java.util.List;

import net.mc_pandacraft.java.plugin.pandacraftutils.PandacraftUtils;
import net.mc_pandacraft.java.plugin.pandacraftutils.config.ConfigManager;
import net.mc_pandacraft.java.plugin.pandacraftutils.config.elements.CommandAliasConfigEntry;
import net.mc_pandacraft.java.plugin.pandacraftutils.players.OnlinePlayer;
import net.mc_pandacraft.java.plugin.pandacraftutils.players.OnlinePlayerManager;

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)
	{
		OnlinePlayer op = OnlinePlayerManager.get(event.getPlayer());
		
		List<CommandAliasConfigEntry> aliases = ConfigManager.getInstance().commandAliasConfig.getCommandAlias();
		for (CommandAliasConfigEntry alias : aliases) {
			
			if (!alias.hasPlayerPermission(op))
				continue;

			String mess = event.getMessage();
			
			if(!mess.toLowerCase().startsWith(alias.getInitialCommand()))
				continue;
			
			mess = mess.replaceFirst("(?i)"+alias.getInitialCommand(), alias.getReplacementCommand());
			
			event.setMessage(mess);
			return;
		}
		
	}
	
	
	
}
