using System.Diagnostics;

namespace OnlineSalesAutoCrop.WS
{
	/// <summary>
	/// 
	/// </summary>
	public static class HeplerFunctions
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="rdPort">Port used by Remote Desktop</param>
		/// <param name="adPort">Port used by AnyDesk</param>
		/// <returns></returns>
		public static string GetRemoteIp(string adPort, string rdPort, out bool isAnyDesk)
		{
			isAnyDesk = false;
			string remoteId = string.Empty;
			adPort = string.IsNullOrEmpty(adPort) ? "7070" : adPort;
			rdPort = string.IsNullOrEmpty(rdPort) ? "3389" : rdPort;

			ProcessStartInfo startInfo = new(fileName: "netstat", arguments: "-n") { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true };
			using Process? process = Process.Start(startInfo: startInfo);
			if (process != null)
			{
				string output = process.StandardOutput.ReadToEnd();
				remoteId = ParseArpResult(output: output, portNo: adPort);
				if (!string.IsNullOrEmpty(remoteId))
				{
					isAnyDesk = true;
				}
				else
				{
					remoteId = ParseArpResult(output: output, portNo: rdPort);
					isAnyDesk = false;
				}
			}

			return remoteId;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="output"></param>
		/// <returns></returns>
		private static string ParseArpResult(string output, string portNo)
		{
			if (string.IsNullOrEmpty(output))
				return string.Empty;

			foreach (string line in output.Split(Environment.NewLine))
			{
				string[] tokens = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
				if (tokens?.Length != 4)
					continue;

				if (!tokens[3].Equals("ESTABLISHED", comparisonType: StringComparison.OrdinalIgnoreCase))
					continue;

				string[] parts = tokens[1].Split(':');
				if (parts.Length == 2 && portNo.Equals(parts[1]))
				{
					parts = tokens[2].Split(':');
					if (parts.Length == 2)
					{
						return parts[0];
					}

					return string.Empty;
				}
			}

			return string.Empty;
		}
	}

	public class NoContentRequest
	{
		public int NoParameter { get; set; }
	}

	public class IpHostResponse
	{
		public int Status { get; set; }
		public string HostName { get; set; } = string.Empty;
		public string IpAddress { get; set; } = string.Empty;
		public string RemoteHost { get; set; } = string.Empty;
		public string MacAddress { get; set; } = string.Empty;
	}

	public class AppSettings
	{
		public required string StartIpBlock { get; set; }
		public required string AnyDeskPort { get; set; }
		public required string RemoteDesktopPort { get; set; }
	}
}
