package net.mc_pandacraft.java.plugin.pandacraftutils.network_api.request_executors;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;

import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import net.mc_pandacraft.java.plugin.pandacraftutils.network_api.Response;
import net.mc_pandacraft.java.plugin.pandacraftutils.players.OnlinePlayerManager;
import net.mc_pandacraft.java.plugin.pandacraftutils.plugin_interface.EssentialsInterface;

public class RequestExecutorPrivateMessage extends AbstractRequestExecutor {
	
	public RequestExecutorPrivateMessage() {
		super("private_message");
	}

	@Override
	protected Response run(String data) {

		String[] dataSplit = data.split(" ", 3);
		if (dataSplit.length != 3)
			return new Response(false, "bad_data : at least two space");
		
		PermissionUser permUser = PermissionsEx.getUser(dataSplit[0]);
		
		if (permUser == null)
			return new Response(false, "user_src_not_exist : user is not registered in permission plugin");
		
		Player p = plugin.getServer().getPlayer(dataSplit[1]);
		
		if (p == null || !p.isOnline()) {
			plugin.getLogger().warning(ChatColor.RED+dataSplit[1]+" n'est pas en ligne");
			return new Response(false, "user_dest_not_online");
		}
		
		String displayName = "["+ChatColor.GRAY+"Console"+ChatColor.GOLD+"]"+permUser.getPrefix() + permUser.getName() + permUser.getSuffix();
		

		String finalMessageToUser = ChatColor.GOLD+"["+displayName+ChatColor.GOLD+" -> moi] "+ChatColor.RESET+dataSplit[2];
		String finalMessageToConsole = ChatColor.GOLD+"["+displayName+ChatColor.GOLD+" -> "+p.getDisplayName()+ChatColor.GOLD+"] "+ChatColor.RESET+dataSplit[2];
		
		plugin.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', finalMessageToConsole));
		p.sendMessage(ChatColor.translateAlternateColorCodes('&', finalMessageToUser));
		
		if (!OnlinePlayerManager.get(p).hasReceiveMessageFromNetworkAPI()) {
			p.sendMessage(ChatColor.GREEN+"Répondez à un message venant de la console avec "+ChatColor.GRAY+"/m console");
		}
		
		
		EssentialsInterface.getPlayer(p).setReplyTo(new CommandSource(plugin.getServer().getConsoleSender()));
		Console.getConsoleReplyTo().setReplyTo(new CommandSource(p));
		
		return new Response(true, "");
	}

}
