using System;
using System.Collections.Generic;
using Tesla;

namespace TeslaConsole;

internal static class PodManager
{
	public delegate void PodReadyConfigHandler(string requestId, byte[] macAddress);

	private const int ConfigPort = 53291;

	private static PodConfigurationServer mServer;

	private static Dictionary<string, byte[]> mActivePods = new Dictionary<string, byte[]>();

	public static List<string> ActiveConfigRequests => new List<string>(mActivePods.Keys);

	public static event PodReadyConfigHandler PodReadyForConfig;

	public static event PodReadyConfigHandler PodConfigured;

	public static void StartConfigurationServer()
	{
		mServer = new PodConfigurationServer(53291, 53292, PodConfigurationRequestHandler);
	}

	private static void PodConfigurationRequestHandler(byte[] macAddress, string requestId)
	{
		lock (mActivePods)
		{
			if (mActivePods.ContainsKey(requestId))
			{
				return;
			}
			mActivePods.Add(requestId, macAddress);
		}
		if (PodManager.PodReadyForConfig != null)
		{
			PodManager.PodReadyForConfig(requestId, macAddress);
		}
	}

	public static byte[] ConfigurePod(string requestId, string passphrase, Pod pod)
	{
		if (PodManager.PodConfigured != null)
		{
			PodManager.PodConfigured(requestId, pod.MacAddress);
		}
		byte[] result = null;
		try
		{
			result = mServer.SendEncryptionKey(passphrase, pod.IPAddress, pod.Subnet, pod.Gateway, pod.DNS, pod.HostName, TimeSpan.FromSeconds(60.0));
		}
		catch (TimeoutException)
		{
		}
		mActivePods.Remove(requestId);
		return result;
	}

	public static byte[] GetMacAddressForRequest(string requestId)
	{
		if (mActivePods.ContainsKey(requestId))
		{
			return mActivePods[requestId];
		}
		return null;
	}
}
