using System;
using System.Collections.Generic;

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

		public override string Description ()
		{
			return "send a message to  the player who last sent you a PM";
		}

		public override string[] Names ()
		{
			return new string[] { "reply", "re" };
		}

		private void SendMessage (ClientInfo _receiver, ClientInfo _sender, string _message)
		{
			PrivateMassageConnections.SetLastPMSender (_sender, _receiver);
			string senderName = CommonMappingFunctions.GetPlayerName (_sender);

			_receiver.netConnection [0].AddToSendQueue (new NetPackage_GameInfoMessage (_message, senderName + " (PM)"));
			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 < 1) {
				m_Console.SendResult ("Usage: reply <message>");
				return;
			}

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

			ClientInfo receiver = PrivateMassageConnections.GetLastPMSenderForPlayer (_sender);
			if (receiver != null && CommonMappingFunctions.GetClientID (receiver) >= 0) {
				SendMessage (receiver, _sender, message);
			} else {
				if (receiver != null) {
					m_Console.SendResult ("The sender of the PM you last received is currently not online.");
				} else {
					m_Console.SendResult ("You have not received a PM so far.");
				}
			}
		}

		public override void ExecuteRemote (string _sender, string[] _params)
		{
			try {
				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 Reply.ExecuteRemote: " + e);
			}
		}

		public override void Run (string[] _params)
		{
			Log.Out ("Command \"reply\" can only be used on clients!");
		}
	}
}
