using System;
using System.Collections.Generic;

namespace AllocsFixes.CustomCommands
{
	public class SayToPlayer : ConsoleCommand
	{
		public SayToPlayer (ConsoleSdtd cons) : base(cons)
		{
		}

		public override string Description ()
		{
			return "send a message to a single player";
		}

		public override string[] Names ()
		{
			return new string[] { "sayplayer", "pm" };
		}

		private void SendMessage (ClientInfo _receiver, ClientInfo _sender, string _message)
		{
			string senderName;
			if (_sender != null) {
				PrivateMassageConnections.SetLastPMSender (_sender, _receiver);
				senderName = CommonMappingFunctions.GetPlayerName (_sender);
			} else {
				senderName = "Server";
			}
			ConnectionManager.Instance.SendPackage (new NetPackage_GameInfoMessage (_message, senderName + " (PM)"), new PackageDestinationSingleEntityID (_receiver.entityId));
			string receiverName = CommonMappingFunctions.GetPlayerName (_receiver);
			m_Console.SendResult ("Message to player " + (receiverName != null ? "\"" + receiverName + "\"" : "unknownName") + " sent with sender \"" + senderName + "\"");
		}

		private void RunInternal (ClientInfo _sender, string[] _params)
		{
			if (_params.Length < 2) {
				m_Console.SendResult ("Usage: sayplayer <playername|entityid> <message>");
				return;
			}

			string message = _params [1];
			for (int i = 2; i < _params.Length; i++) {
				message += " " + _params [i];
			}

			ClientInfo receiver = CommonMappingFunctions.GetClientInfoFromNameOrID (_params [0], true);
			if (receiver != null) {
				SendMessage (receiver, _sender, message);
			} else {
				m_Console.SendResult ("Playername or entity ID not found.");
			}
		}

		public override void ExecuteRemote (string _sender, string[] _params)
		{
			try {
				this.m_Console.SendResult (string.Format ("{0} executing remote command '{1}' {2}", _sender, this.Names () [0], string.Join (" ", _params)));
				ClientInfo ci = CommonMappingFunctions.GetClientInfoFromSteamID (_sender);
				RunInternal (ci, _params);
			} catch (Exception e) {
				Log.Out ("Error in SayToPlayer.ExecuteRemote: " + e);
			}
		}

		public override void Run (string[] _params)
		{
			try {
				RunInternal (null, _params);
			} catch (Exception e) {
				Log.Out ("Error in SayToPlayer.Run: " + e);
			}
		}
	}
}
