using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
using QC.MCI;

namespace QC.MultiplexManager;

public class MultiplexManagerImp
{
	public enum TE_Port_Dir
	{
		Analyzer,
		Generator
	}

	private enum Separator
	{
		SemiColon,
		Colon,
		Comma
	}

	private const int LockIndefinitely = -1;

	private const int WaitIndefinitely = -1;

	private const string MultiplexerMutexName = "MULTI_DUT_MUTEX___MULTIPLEXER_ID_";

	private const string MultiplexManagerQueueMutexName = "QC_MULTIPLEX_MANAGER_QUEUE___GROUP_ID_";

	private const string MultiplexManagerQueueName = "QC_MM_QUEUE_NAME___GROUP_ID_";

	private const int maxNumberOfDUTs = 64;

	private string cfg_filename = "";

	private int dut_index_from_GV;

	private string single_tree_timeout = "";

	private DutInformation all_dut_info;

	private static Dictionary<string, MemoryMappedFile> mmFiles = new Dictionary<string, MemoryMappedFile>();

	private char[] semiColon = new char[1] { ';' };

	private char[] Colon = new char[1] { ':' };

	private char[] Comma = new char[1] { ',' };

	private string CfgFilenameFromGV
	{
		get
		{
			cfg_filename = EnvManager.GetInstance().GetGlobalVariable("MULTIPLEX_MANAGER_CONFIG_FILE");
			if (cfg_filename.Length == 0)
			{
				throw new Exception("QSPR Global Variable MULTIPLEX_MANAGER_CONFIG_FILE has not been set!");
			}
			return cfg_filename;
		}
	}

	private int DutIndexFromGV
	{
		get
		{
			string globalVariable = EnvManager.GetInstance().GetGlobalVariable("DUT_INDEX");
			if (globalVariable.Length == 0)
			{
				throw new Exception("QSPR Global Variable DUT_INDEX has not been set!");
			}
			dut_index_from_GV = Convert.ToInt32(globalVariable);
			return dut_index_from_GV;
		}
	}

	private int SingleTreeTimeout
	{
		get
		{
			single_tree_timeout = EnvManager.GetInstance().GetGlobalVariable("XTT_TIMEOUT");
			if (single_tree_timeout.Length == 0)
			{
				throw new Exception("QSPR Global Variable XTT_TIMEOUT has not been set!");
			}
			return Convert.ToInt32(single_tree_timeout);
		}
	}

	private DutInformation AllDutInfo
	{
		get
		{
			if (all_dut_info == null)
			{
				all_dut_info = new DutInformation();
			}
			return all_dut_info;
		}
	}

	public bool UnlockResourceImp(InputParameterSource Input_Parameter_Source, string Multiplex_Manager_Config_File, int DUT_Number)
	{
		bool result = true;
		try
		{
			LogHeader("UnlockResource");
			if (Input_Parameter_Source == InputParameterSource.QSPR_GLOBAL_VARIABLES)
			{
				Multiplex_Manager_Config_File = CfgFilenameFromGV;
				DUT_Number = DutIndexFromGV;
			}
			DutCfg dutInfo = AllDutInfo.GetDutInfo(Multiplex_Manager_Config_File, DUT_Number);
			RemoveFromQueue(dutInfo, DUT_Number);
		}
		catch (Exception ex)
		{
			EnvManager.GetInstance().DebugMessageWrite("Error", ex.Message);
			result = false;
		}
		return result;
	}

	public bool LockResourceImp(InputParameterSource Input_Parameter_Source, string Multiplex_Manager_Config_File, int DUT_Number, int Lock_Acq_Timeout)
	{
		bool flag = false;
		try
		{
			LogHeader("LockResource");
			if (Input_Parameter_Source == InputParameterSource.QSPR_GLOBAL_VARIABLES)
			{
				Multiplex_Manager_Config_File = CfgFilenameFromGV;
				DUT_Number = DutIndexFromGV;
			}
			DutCfg dutInfo = AllDutInfo.GetDutInfo(Multiplex_Manager_Config_File, DUT_Number);
			int numDutsInGroup = AllDutInfo.GetNumDutsInGroup(dutInfo.GroupID);
			if (Input_Parameter_Source == InputParameterSource.QSPR_GLOBAL_VARIABLES)
			{
				int num = SingleTreeTimeout * (numDutsInGroup - 1);
				EnvManager.GetInstance().SetGlobalVariable("XTT_TIMEOUT_OFFSET", num.ToString());
				int num2 = SingleTreeTimeout + num;
				EnvManager.GetInstance().DebugMessageWrite("Debug", "Tree timeout for DUT " + DUT_Number + " in Group " + dutInfo.GroupID + " with " + numDutsInGroup + " DUTs: " + num2 + " sec");
				Lock_Acq_Timeout = SingleTreeTimeout * (numDutsInGroup - 1);
			}
			if (Lock_Acq_Timeout > 0)
			{
				TimeSpan timeSpan = TimeSpan.FromSeconds(Convert.ToDouble(Lock_Acq_Timeout));
				EnvManager.GetInstance().DebugMessageWrite("Debug", "Mutex lock acquisition timeout: " + timeSpan.Hours.ToString().PadLeft(2, '0') + ":" + timeSpan.Minutes.ToString().PadLeft(2, '0') + ":" + timeSpan.Seconds.ToString().PadLeft(2, '0') + ":" + timeSpan.Milliseconds.ToString().PadLeft(3, '0'));
				Lock_Acq_Timeout *= 1000;
			}
			else
			{
				Lock_Acq_Timeout = -1;
				EnvManager.GetInstance().DebugMessageWrite("Debug", "Mutex lock acquisition timeout: Wait indefinitely");
			}
			return WaitInQueue(dutInfo, DUT_Number, Lock_Acq_Timeout);
		}
		catch (Exception ex)
		{
			EnvManager.GetInstance().DebugMessageWrite("Error", ex.Message);
			return false;
		}
	}

	public void BuildCalPathNumbers(ref string sCalPathNumbers, string CalPathNumber)
	{
		if (sCalPathNumbers.Length == 0)
		{
			sCalPathNumbers += CalPathNumber;
			return;
		}
		sCalPathNumbers += ":";
		sCalPathNumbers += CalPathNumber;
	}

	private string[] Split(Separator sepType, string stringToBeSplitted)
	{
		stringToBeSplitted = Regex.Replace(stringToBeSplitted, "[ \n\r\t]", "");
		return sepType switch
		{
			Separator.Colon => stringToBeSplitted.Split(Colon, StringSplitOptions.RemoveEmptyEntries), 
			Separator.SemiColon => stringToBeSplitted.Split(semiColon, StringSplitOptions.RemoveEmptyEntries), 
			_ => stringToBeSplitted.Split(Comma, StringSplitOptions.RemoveEmptyEntries), 
		};
	}

	public void BuildRoutingConfig_V2(ref List<string> ListOfCurrentPort, TE_Port_Dir te_port_Dir, string routingConfig, ref string sCalPathNumber, string CalNumberFromRoutingConfig, ref string sCalPathConfigName, string ConfigNameFromRoutingConfig)
	{
		string[] array = Split(Separator.SemiColon, routingConfig);
		if (ListOfCurrentPort.Count != array.Length)
		{
			for (int i = 0; i < array.Length; i++)
			{
				ListOfCurrentPort.Add("");
			}
		}
		bool flag = false;
		for (int j = 0; j < array.Length; j++)
		{
			string text = array[j].Split(Colon, StringSplitOptions.RemoveEmptyEntries)[0];
			string text2 = array[j].Split(Colon, StringSplitOptions.RemoveEmptyEntries)[1];
			if (te_port_Dir == TE_Port_Dir.Generator)
			{
				if (ListOfCurrentPort[j].Length != 0 && !ListOfCurrentPort[j].Contains(text2))
				{
					ListOfCurrentPort[j] = ListOfCurrentPort[j] + "," + text2;
					flag = true;
				}
				if (ListOfCurrentPort[j].Length == 0)
				{
					ListOfCurrentPort[j] = text2;
					flag = true;
				}
			}
			if (te_port_Dir == TE_Port_Dir.Analyzer)
			{
				if (ListOfCurrentPort[j].Length != 0 && !ListOfCurrentPort[j].Contains(text))
				{
					ListOfCurrentPort[j] = ListOfCurrentPort[j] + "," + text;
					flag = true;
				}
				if (ListOfCurrentPort[j].Length == 0)
				{
					ListOfCurrentPort[j] = text;
					flag = true;
				}
			}
		}
		if (flag)
		{
			if (sCalPathNumber.Length == 0)
			{
				sCalPathNumber = CalNumberFromRoutingConfig;
			}
			else
			{
				sCalPathNumber = sCalPathNumber + "," + CalNumberFromRoutingConfig;
			}
			if (sCalPathConfigName.Length == 0)
			{
				sCalPathConfigName = ConfigNameFromRoutingConfig;
			}
			else
			{
				sCalPathConfigName = sCalPathConfigName + "," + ConfigNameFromRoutingConfig;
			}
		}
	}

	public void BuildRoutingConfig(ref string currentRoutingConfig, TE_Port_Dir te_port_Dir, string routingConfig)
	{
		List<string> list = new List<string>();
		List<string> list2 = new List<string>();
		char[] separator = new char[1] { ';' };
		char[] separator2 = new char[1] { ':' };
		routingConfig = Regex.Replace(routingConfig, "[ \n\r\t]", "");
		int num = routingConfig.Split(separator, StringSplitOptions.RemoveEmptyEntries).Length;
		if (currentRoutingConfig.Length > 0)
		{
			string[] array = currentRoutingConfig.Split(separator, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string item = array[i].Split(separator2)[0];
				string item2 = array[i].Split(separator2)[1];
				list.Add(item);
				list2.Add(item2);
			}
		}
		else
		{
			for (int j = 0; j < num; j++)
			{
				list2.Add("");
				list.Add("");
			}
		}
		string[] array2 = routingConfig.Split(separator, StringSplitOptions.RemoveEmptyEntries);
		for (int k = 0; k < array2.Length; k++)
		{
			string text = array2[k].Split(separator2, StringSplitOptions.RemoveEmptyEntries)[0];
			string text2 = array2[k].Split(separator2, StringSplitOptions.RemoveEmptyEntries)[1];
			if (te_port_Dir == TE_Port_Dir.Generator)
			{
				if (list2[k].Length != 0)
				{
					list2[k] = list2[k] + "," + text2;
				}
				else
				{
					list2[k] = text2;
				}
			}
			if (te_port_Dir == TE_Port_Dir.Analyzer)
			{
				if (list[k].Length != 0)
				{
					list[k] = list[k] + "," + text;
				}
				else
				{
					list[k] = text;
				}
			}
		}
		currentRoutingConfig = "";
		for (int l = 0; l < num; l++)
		{
			string text3 = list[l] + ":" + list2[l];
			if (l == 0)
			{
				currentRoutingConfig = text3;
			}
			else
			{
				currentRoutingConfig = currentRoutingConfig + ";" + text3;
			}
		}
	}

	public bool SetPortsPathsGlobalVariableImp(InputParameterSource Input_Parameter_Source, string Multiplex_Manager_Config_File, int dut)
	{
		DutCfg dutInfo = AllDutInfo.GetDutInfo(Multiplex_Manager_Config_File, dut);
		MuxCfg muxCfg = dutInfo.MultiplexerCfgList[0];
		string[] array = Split(Separator.Comma, GetAntennasTokenS(muxCfg));
		EnvManager.GetInstance().SetGlobalVariable("MultiplexerType", dutInfo.MultiplexerType.ToString());
		EnvManager.GetInstance().DebugMessageWrite("Debug", "MultiplexerType " + dutInfo.MultiplexerType);
		if (dutInfo.MultiplexerType == 0)
		{
			return false;
		}
		List<string> ListOfCurrentPort = new List<string>();
		List<string> ListOfCurrentPort2 = new List<string>();
		string sCalPathNumber = "";
		string sCalPathNumber2 = "";
		string sCalPathConfigName = "";
		string sCalPathConfigName2 = "";
		for (int i = 0; i < dut; i++)
		{
			ListOfCurrentPort.Add("");
		}
		bool flag = false;
		for (int j = 0; j < array.Length; j++)
		{
			flag = false;
			for (int k = 0; k < muxCfg.Mux.RoutingList.Length; k++)
			{
				if (Contain(muxCfg.Mux.RoutingList[k].Ports, array[j]))
				{
					BuildRoutingConfig_V2(ref ListOfCurrentPort, TE_Port_Dir.Analyzer, muxCfg.Mux.RoutingList[k].Routing_Config, ref sCalPathNumber, muxCfg.Mux.RoutingList[k].Tx_Cal_Path_Number, ref sCalPathConfigName, muxCfg.Mux.RoutingList[k].Tx_Cal_Path_Config_Name);
					BuildRoutingConfig_V2(ref ListOfCurrentPort2, TE_Port_Dir.Generator, muxCfg.Mux.RoutingList[k].Routing_Config, ref sCalPathNumber2, muxCfg.Mux.RoutingList[k].Rx_Cal_Path_Number, ref sCalPathConfigName2, muxCfg.Mux.RoutingList[k].Rx_Cal_Path_Config_Name);
					flag = true;
				}
			}
			if (!flag)
			{
				ListOfCurrentPort[dut - 1] += ",";
				sCalPathNumber += ",";
				sCalPathNumber2 += ",";
			}
		}
		string text = string.Join(";", ListOfCurrentPort[dut - 1]);
		EnvManager.GetInstance().DebugMessageWrite("Debug", "MM_Ports_For_AntNumbers " + text);
		SetGlobalVariable("MM_Ports_For_AntNumbers", text);
		string text2 = sCalPathNumber + ":" + sCalPathNumber2;
		EnvManager.GetInstance().DebugMessageWrite("Debug", "MM_Paths_For_AntNumbers " + text2);
		EnvManager.GetInstance().SetGlobalVariable("MM_Paths_For_AntNumbers", text2);
		if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(sCalPathNumber))
		{
			return false;
		}
		return true;
	}

	public bool SwitchPathAntennaNumbersImp(InputParameterSource Input_Parameter_Source, string Multiplex_Manager_Config_File, int DUT_Number, string Tx_Antenna_Numbers, string Rx_Antenna_Numbers, string Technology_Code)
	{
		LogHeader("SwitchPathByAntennaNumbers");
		StartTPLContext("SwitchPathByAntennaNumbers");
		bool result = false;
		EnvManager.GetInstance().SetGlobalVariable("MM_DISABLE_RF_PORT_SELECTION_IN_NON_MM_NODE", "1");
		try
		{
			DutCfg dutInfo = AllDutInfo.GetDutInfo(Multiplex_Manager_Config_File, DUT_Number);
			for (int i = 0; i < dutInfo.MultiplexerCfgList.Count; i++)
			{
				MuxCfg muxCfg = dutInfo.MultiplexerCfgList[i];
				string text = "MULTI_DUT_MUTEX___MULTIPLEXER_ID_" + muxCfg.Mux.MultiplexerID;
				Mutex mutex = new Mutex(initiallyOwned: false, text);
				if (mutex.WaitOne(60000))
				{
					try
					{
						MultiplexControlInterface muxCtrlInterface = muxCfg.MuxCtrlInterface;
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Multiplexer ID: " + muxCfg.Mux.MultiplexerID);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Driver DLL: " + muxCfg.Mux.DriverDLL);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Configuration: " + muxCtrlInterface.RoutingConfiguration);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Bus Configuration: " + muxCtrlInterface.BusConfiguration);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Tx Ant: " + Tx_Antenna_Numbers);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Rx Ant: " + Rx_Antenna_Numbers);
						if (muxCtrlInterface.SimulationMode)
						{
							EnvManager.GetInstance().DebugMessageWrite("Debug", "********************************");
							EnvManager.GetInstance().DebugMessageWrite("Debug", "SIMULATION MODE                 ");
							EnvManager.GetInstance().DebugMessageWrite("Debug", "********************************");
						}
						else
						{
							EnvManager.GetInstance().DebugMessageWrite("Debug", " Simulation Mode: False");
						}
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Switching Multiplexer " + muxCfg.Mux.MultiplexerID + " to DUT number " + DUT_Number + "\n");
						string[] array = Split(Separator.Comma, Tx_Antenna_Numbers);
						string[] array2 = Split(Separator.Comma, Rx_Antenna_Numbers);
						string text2 = "";
						string sCalPathNumber = "";
						string sCalPathNumber2 = "";
						string sCalPathConfigName = "";
						string sCalPathConfigName2 = "";
						List<string> ListOfCurrentPort = new List<string>();
						List<string> ListOfCurrentPort2 = new List<string>();
						for (int j = 0; j < muxCfg.Mux.RoutingList.Length; j++)
						{
							for (int k = 0; k < array.Length; k++)
							{
								if (Contain(muxCfg.Mux.RoutingList[j].Ports, array[k]))
								{
									BuildRoutingConfig_V2(ref ListOfCurrentPort, TE_Port_Dir.Analyzer, muxCfg.Mux.RoutingList[j].Routing_Config, ref sCalPathNumber, muxCfg.Mux.RoutingList[j].Tx_Cal_Path_Number, ref sCalPathConfigName, muxCfg.Mux.RoutingList[j].Tx_Cal_Path_Config_Name);
								}
							}
						}
						for (int l = 0; l < muxCfg.Mux.RoutingList.Length; l++)
						{
							for (int m = 0; m < array2.Length; m++)
							{
								if (Contain(muxCfg.Mux.RoutingList[l].Ports, array2[m]))
								{
									BuildRoutingConfig_V2(ref ListOfCurrentPort2, TE_Port_Dir.Generator, muxCfg.Mux.RoutingList[l].Routing_Config, ref sCalPathNumber2, muxCfg.Mux.RoutingList[l].Rx_Cal_Path_Number, ref sCalPathConfigName2, muxCfg.Mux.RoutingList[l].Rx_Cal_Path_Config_Name);
								}
							}
						}
						for (int n = 0; n < ListOfCurrentPort2.Count; n++)
						{
							string text3 = text2;
							text2 = text3 + ListOfCurrentPort[n] + ":" + ListOfCurrentPort2[n] + ";";
						}
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Cal DB: Tx Cal Path Numbers " + sCalPathNumber);
						EnvManager.GetInstance().SetGlobalVariable("MCI_TX_CAL_PATH_NUMBERS", sCalPathNumber);
						EnvManager.GetInstance().SetGlobalVariable("MCI_TX_CAL_PATH_NUMBERS_DUT" + DUT_Number, sCalPathNumber);
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Cal DB: Rx Cal Path Numbers " + sCalPathNumber2);
						EnvManager.GetInstance().SetGlobalVariable("MCI_RX_CAL_PATH_NUMBERS", sCalPathNumber2);
						EnvManager.GetInstance().SetGlobalVariable("MCI_RX_CAL_PATH_NUMBERS_DUT" + DUT_Number, sCalPathNumber2);
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Cal DB: Tx Cal Config Name used by Connectivity " + sCalPathConfigName);
						EnvManager.GetInstance().SetGlobalVariable("MCI_TX_CAL_CONFIG_NAME", sCalPathConfigName);
						EnvManager.GetInstance().SetGlobalVariable("MCI_TX_CAL_CONFIG_NAME_DUT" + DUT_Number, sCalPathNumber);
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Cal DB: Rx Cal Config Name used by Connectivity " + sCalPathConfigName2);
						EnvManager.GetInstance().SetGlobalVariable("MCI_RX_CAL_CONFIG_NAME", sCalPathConfigName2);
						EnvManager.GetInstance().SetGlobalVariable("MCI_RX_CAL_CONFIG_NAME_DUT" + DUT_Number, sCalPathNumber);
						EnvManager.GetInstance().SetGlobalVariable("MULTIPLEX_MANAGER_CONFIG_FILE", Multiplex_Manager_Config_File);
						muxCtrlInterface.RoutingConfiguration = text2;
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Switching Multiplexer: Routing configuration string is " + text2 + "\n");
						muxCtrlInterface.EnablePath(dutInfo.MultiplexerCfgList[i].Path, Technology_Code);
						result = true;
					}
					catch (Exception ex)
					{
						EnvManager.GetInstance().DebugMessageWrite("Debug", "MM: " + ex.Message);
					}
					finally
					{
						mutex.ReleaseMutex();
					}
					continue;
				}
				throw new TimeoutException("Failed to aquire Multiplexer Mutex: " + text + ". Check the execution time of the Multiplex Controller Interface being used.");
			}
		}
		catch (Exception ex2)
		{
			EnvManager.GetInstance().DebugMessageWrite("Error", ex2.Message);
			result = false;
		}
		StopTPLContext();
		return result;
	}

	public bool SwitchPathImp(InputParameterSource Input_Parameter_Source, string Multiplex_Manager_Config_File, int DUT_Number, string Requested_RF_Ports, string Requested_Bands)
	{
		bool result = true;
		string techInfo = "";
		try
		{
			LogHeader("SwitchPath");
			StartTPLContext("SwitchPath");
			if (Input_Parameter_Source == InputParameterSource.QSPR_GLOBAL_VARIABLES)
			{
				Multiplex_Manager_Config_File = CfgFilenameFromGV;
				DUT_Number = DutIndexFromGV;
			}
			EnvManager.GetInstance().SetGlobalVariable("MM_DISABLE_RF_PORT_SELECTION_IN_NON_MM_NODE", "1");
			Requested_RF_Ports = Requested_RF_Ports.ToUpper();
			int num = 0;
			if (Requested_RF_Ports.StartsWith("WCDMA") || Requested_RF_Ports.Contains("_WCDMA_"))
			{
				techInfo = "WCDMA";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("CDMA") || Requested_RF_Ports.Contains("_CDMA_"))
			{
				techInfo = "CDMA";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("GSM") || Requested_RF_Ports.Contains("_GSM_"))
			{
				techInfo = "GSM";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("TDSCDMA") || Requested_RF_Ports.Contains("_TDSCDMA_"))
			{
				techInfo = "TDSCDMA";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("LTE") || Requested_RF_Ports.Contains("_LTE_"))
			{
				techInfo = "LTE";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("GNSS") || Requested_RF_Ports.Contains("_GNSS_"))
			{
				techInfo = "GNSS";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("BT") || Requested_RF_Ports.Contains("_BT_"))
			{
				techInfo = "BT";
				num++;
			}
			if (Requested_RF_Ports.StartsWith("WLAN") || Requested_RF_Ports.Contains("_WLAN_"))
			{
				techInfo = "WLAN";
				num++;
			}
			if (num > 1)
			{
				throw new Exception("Error: More than one technology was specified in the Requested RF Ports.");
			}
			if (num == 0)
			{
				throw new Exception("Error: Unknown technology was specified in the Requested RF Ports.");
			}
			DutCfg dutInfo = AllDutInfo.GetDutInfo(Multiplex_Manager_Config_File, DUT_Number);
			for (int i = 0; i < dutInfo.MultiplexerCfgList.Count; i++)
			{
				MuxCfg muxCfg = dutInfo.MultiplexerCfgList[i];
				string text = "MULTI_DUT_MUTEX___MULTIPLEXER_ID_" + muxCfg.Mux.MultiplexerID;
				Mutex mutex = new Mutex(initiallyOwned: false, text);
				if (mutex.WaitOne(60000))
				{
					try
					{
						muxCfg.Port = Requested_RF_Ports;
						MultiplexControlInterface muxCtrlInterface = muxCfg.MuxCtrlInterface;
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Multiplexer ID: " + muxCfg.Mux.MultiplexerID);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Driver DLL: " + muxCfg.Mux.DriverDLL);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Configuration: " + muxCtrlInterface.RoutingConfiguration);
						EnvManager.GetInstance().DebugMessageWrite("Debug", " Bus Configuration: " + muxCtrlInterface.BusConfiguration);
						if (muxCtrlInterface.SimulationMode)
						{
							EnvManager.GetInstance().DebugMessageWrite("Debug", "********************************");
							EnvManager.GetInstance().DebugMessageWrite("Debug", "SIMULATION MODE                 ");
							EnvManager.GetInstance().DebugMessageWrite("Debug", "********************************");
						}
						else
						{
							EnvManager.GetInstance().DebugMessageWrite("Debug", " Simulation Mode: False");
						}
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Switching Multiplexer " + muxCfg.Mux.MultiplexerID + " to DUT number " + DUT_Number + "\n");
						bool flag = false;
						if (Requested_RF_Ports == "" && Requested_Bands == "" && muxCfg.Mux.RoutingList.Length == 1)
						{
							muxCtrlInterface.RoutingConfiguration = muxCfg.Mux.RoutingList[0].Routing_Config;
							EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Configuration for " + muxCfg.Mux.RoutingList[0].Ports.ToString() + ": " + muxCtrlInterface.RoutingConfiguration);
							muxCtrlInterface.EnablePath(dutInfo.MultiplexerCfgList[i].Path, techInfo);
							flag = true;
							goto IL_08a9;
						}
						if (Requested_RF_Ports == "" && Requested_Bands == "" && muxCfg.Mux.RoutingList.Length > 1)
						{
							throw new Exception("Error: Requested RF Port was not specified and there is more than one Routing Configuration present in the Multiplex Manager Configuration file.");
						}
						bool flag2 = false;
						bool flag3 = false;
						string[] array = Requested_RF_Ports.Replace(" ", string.Empty).Split(',');
						string[] array2 = Requested_Bands.Replace(" ", string.Empty).Split(',');
						for (int j = 0; j < muxCfg.Mux.RoutingList.Length; j++)
						{
							if (!(muxCfg.Mux.RoutingList[j].Ports != ""))
							{
								continue;
							}
							bool flag4 = true;
							string[] array3 = array;
							foreach (string token in array3)
							{
								if (Contain(muxCfg.Mux.RoutingList[j].Ports, token))
								{
									flag2 = true;
								}
								else
								{
									flag4 = false;
								}
							}
							if (!flag4)
							{
								continue;
							}
							bool flag5 = true;
							string[] array4 = array2;
							foreach (string text2 in array4)
							{
								if (text2 != "")
								{
									if (Contain(muxCfg.Mux.RoutingList[j].Bands.ToUpper(), text2))
									{
										flag3 = true;
									}
									else
									{
										flag5 = false;
									}
								}
							}
							if (flag5)
							{
								muxCtrlInterface.RoutingConfiguration = muxCfg.Mux.RoutingList[j].Routing_Config;
								EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Description: " + muxCfg.Mux.RoutingList[j].Description.ToString());
								EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Configuration for PORTS:" + muxCfg.Mux.RoutingList[j].Ports.ToString() + "    BANDS:" + muxCfg.Mux.RoutingList[j].Bands.ToString() + ": is" + muxCtrlInterface.RoutingConfiguration);
								muxCtrlInterface.EnablePath(dutInfo.MultiplexerCfgList[i].Path, techInfo);
								flag = true;
								break;
							}
						}
						if (!flag && !flag2)
						{
							for (int m = 0; m < muxCfg.Mux.RoutingList.Length; m++)
							{
								if (muxCfg.Mux.RoutingList[m].Ports == "")
								{
									muxCtrlInterface.RoutingConfiguration = muxCfg.Mux.RoutingList[m].Routing_Config;
									EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Configuration for " + muxCfg.Mux.RoutingList[m].Ports.ToString() + ": " + muxCtrlInterface.RoutingConfiguration);
									muxCtrlInterface.EnablePath(dutInfo.MultiplexerCfgList[i].Path, techInfo);
									flag = true;
									break;
								}
							}
						}
						else if (!flag && !flag3)
						{
							for (int n = 0; n < muxCfg.Mux.RoutingList.Length; n++)
							{
								if (!(muxCfg.Mux.RoutingList[n].Ports != ""))
								{
									continue;
								}
								bool flag6 = true;
								string[] array5 = array;
								foreach (string token2 in array5)
								{
									if (!Contain(muxCfg.Mux.RoutingList[n].Ports, token2))
									{
										flag6 = false;
									}
								}
								if (!flag6)
								{
									continue;
								}
								string[] array6 = array2;
								for (int num3 = 0; num3 < array6.Length; num3++)
								{
									_ = array6[num3];
									if (muxCfg.Mux.RoutingList[n].Bands == "")
									{
										muxCtrlInterface.RoutingConfiguration = muxCfg.Mux.RoutingList[n].Routing_Config;
										EnvManager.GetInstance().DebugMessageWrite("Debug", " Routing Configuration for " + muxCfg.Mux.RoutingList[n].Ports.ToString() + ": " + muxCtrlInterface.RoutingConfiguration);
										muxCtrlInterface.EnablePath(dutInfo.MultiplexerCfgList[i].Path, techInfo);
										flag = true;
										break;
									}
								}
							}
						}
						if (!flag)
						{
							goto IL_08a9;
						}
						goto end_IL_01fe;
						IL_08a9:
						if (!flag)
						{
							throw new Exception("Unable to find a ROUTING_CONFIG entry that contains all the requested PORTS and BANDSin the Multiplex Manager configuration file.\nPORTS:" + Requested_RF_Ports + "\nBANDS:" + Requested_Bands);
						}
						EnvManager.GetInstance().DebugMessageWrite("Debug", "Switching Multiplexer " + muxCfg.Mux.MultiplexerID + " to DUT number " + DUT_Number + "\n");
						continue;
						end_IL_01fe:;
					}
					finally
					{
						mutex.ReleaseMutex();
					}
					break;
				}
				throw new TimeoutException("Failed to aquire Multiplexer Mutex: " + text + ". Check the execution time of the Multiplex Controller Interface being used.");
			}
		}
		catch (Exception ex)
		{
			EnvManager.GetInstance().DebugMessageWrite("Error", ex.Message);
			result = false;
		}
		StopTPLContext();
		return result;
	}

	public bool GetDutAndGroupIDsImp(InputParameterSource Input_Parameter_Source, string Multiplex_Manager_Config_File, out string Dut_IDs, out string Group_IDs)
	{
		bool result = true;
		Dut_IDs = "";
		Group_IDs = "";
		try
		{
			if (Input_Parameter_Source == InputParameterSource.QSPR_GLOBAL_VARIABLES)
			{
				Multiplex_Manager_Config_File = CfgFilenameFromGV;
			}
			AllDutInfo.ExtractInfoForAllDuts(Multiplex_Manager_Config_File);
			AllDutInfo.GetDutAndGroupIds(out Dut_IDs, out Group_IDs);
		}
		catch (Exception ex)
		{
			EnvManager.GetInstance().DebugMessageWrite("Error", ex.Message);
			result = false;
		}
		return result;
	}

	private bool Contain(string CommaDelimitedString, string token)
	{
		bool result = false;
		token = token.ToUpper();
		CommaDelimitedString = CommaDelimitedString.ToUpper();
		char[] separator = new char[1] { ',' };
		string[] array = CommaDelimitedString.Split(separator, StringSplitOptions.RemoveEmptyEntries);
		if (array.Length == 0)
		{
			return result = false;
		}
		for (int i = 0; i < array.Length; i++)
		{
			if (token == array[i])
			{
				return result = true;
			}
		}
		return result;
	}

	public string GetGlobalVariable(string name)
	{
		return EnvManager.GetInstance().GetGlobalVariable(name);
	}

	public void SetGlobalVariable(string name, string value)
	{
		EnvManager.GetInstance().SetGlobalVariable(name, value);
	}

	private void LogHeader(string callingMethod)
	{
		string text;
		try
		{
			text = EnvManager.GetInstance().QTMInfoGetTestName();
		}
		catch (Exception)
		{
			text = callingMethod;
		}
		EnvManager.GetInstance().DebugMessageWrite("Debug", "====================================");
		EnvManager.GetInstance().DebugMessageWrite("Debug", text);
		EnvManager.GetInstance().DebugMessageWrite("Debug", "====================================");
	}

	private void StartTPLContext(string callingMethod)
	{
		string text;
		try
		{
			text = EnvManager.GetInstance().QTMInfoGetTestName();
		}
		catch (Exception)
		{
			text = callingMethod;
		}
		EnvManager.GetInstance().DebugMessageTPLStartContext("TPL2", text + " MultipexManager " + callingMethod, "ALG");
	}

	private void StopTPLContext()
	{
		EnvManager.GetInstance().DebugMessageTPLStopContext("TPL2");
	}

	private string GetAntennasTokenS(MuxCfg muxCfg)
	{
		int num = 0;
		for (int i = 0; i < muxCfg.Mux.RoutingList.Length; i++)
		{
			string[] array = muxCfg.Mux.RoutingList[i].Ports.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
			for (int j = 0; j < array.Length; j++)
			{
				int result = 0;
				int.TryParse(array[j].Replace("WWAN_ANT", ""), out result);
				if (result > num)
				{
					num = result;
				}
			}
		}
		string text = "";
		for (int k = 0; k <= num; k++)
		{
			text = text + "WWAN_ANT" + k + ",";
		}
		return text;
	}

	private bool WaitInQueue(DutCfg DutConfig, int DUT_Number, int Lock_Acq_Timeout_ms)
	{
		bool result = true;
		bool flag = false;
		string text = "QC_MM_QUEUE_NAME___GROUP_ID_" + DutConfig.GroupID;
		Mutex mutex = new Mutex(initiallyOwned: false, "QC_MULTIPLEX_MANAGER_QUEUE___GROUP_ID_" + DutConfig.GroupID);
		if (mutex.WaitOne(60000))
		{
			try
			{
				if (!mmFiles.ContainsKey(text))
				{
					try
					{
						MemoryMappedFile value = MemoryMappedFile.OpenExisting(text);
						mmFiles.Add(text, value);
					}
					catch (FileNotFoundException)
					{
						MemoryMappedFileSecurity memoryMappedFileSecurity = new MemoryMappedFileSecurity();
						memoryMappedFileSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
						MemoryMappedFile value2 = MemoryMappedFile.CreateNew(text, 64L, MemoryMappedFileAccess.ReadWrite);
						mmFiles.Add(text, value2);
						MemoryMappedViewAccessor memoryMappedViewAccessor = mmFiles[text].CreateViewAccessor();
						byte value3 = 0;
						for (int i = 0; i < 64; i++)
						{
							memoryMappedViewAccessor.Write(i, value3);
						}
					}
				}
				MemoryMappedFile memoryMappedFile = mmFiles[text];
				MemoryMappedViewAccessor memoryMappedViewAccessor2 = memoryMappedFile.CreateViewAccessor();
				byte structure = 0;
				memoryMappedViewAccessor2.Read<byte>(0L, out structure);
				if (structure != 0 && structure != (byte)DUT_Number)
				{
					flag = true;
					for (int j = 1; j < 64; j++)
					{
						byte structure2 = 0;
						memoryMappedViewAccessor2.Read<byte>(j, out structure2);
						if (structure2 == 0)
						{
							memoryMappedViewAccessor2.Write(j, (byte)DUT_Number);
							break;
						}
					}
				}
				else
				{
					memoryMappedViewAccessor2.Write(0L, (byte)DUT_Number);
				}
				memoryMappedViewAccessor2.Dispose();
			}
			finally
			{
				mutex.ReleaseMutex();
			}
			if (flag)
			{
				int tickCount = Environment.TickCount;
				bool flag2 = false;
				while (flag)
				{
					if (flag2)
					{
						EnvManager.GetInstance().DebugMessageWrite("Error", "Timeout while waiting to aquire the lock for DUT: " + DUT_Number + ". Increase the XTT_TIMEOUT to account for XTT execution time and the number of DUTs being used.");
						result = false;
						break;
					}
					flag2 = Environment.TickCount - tickCount > Lock_Acq_Timeout_ms;
					Thread.Sleep(50);
					if (mutex.WaitOne(60000))
					{
						try
						{
							MemoryMappedViewAccessor memoryMappedViewAccessor3 = mmFiles[text].CreateViewAccessor();
							byte structure3 = 0;
							memoryMappedViewAccessor3.Read<byte>(0L, out structure3);
							if (structure3 == (byte)DUT_Number)
							{
								flag = false;
							}
						}
						finally
						{
							mutex.ReleaseMutex();
						}
					}
					else
					{
						result = false;
					}
				}
			}
		}
		else
		{
			EnvManager.GetInstance().DebugMessageWrite("Error", "Failed to acquire Queue Lock: QC_MULTIPLEX_MANAGER_QUEUE___GROUP_ID_" + DutConfig.GroupID);
			result = false;
		}
		return result;
	}

	private void RemoveFromQueue(DutCfg DutConfig, int DUT_Number)
	{
		Mutex mutex = new Mutex(initiallyOwned: false, "QC_MULTIPLEX_MANAGER_QUEUE___GROUP_ID_" + DutConfig.GroupID);
		try
		{
			MemoryMappedFile memoryMappedFile = MemoryMappedFile.OpenExisting("QC_MM_QUEUE_NAME___GROUP_ID_" + DutConfig.GroupID);
			if (mutex.WaitOne(60000))
			{
				try
				{
					MemoryMappedViewAccessor memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor();
					byte structure = 0;
					int num = 0;
					for (int i = 0; i < 64; i++)
					{
						memoryMappedViewAccessor.Read<byte>(num, out structure);
						if (structure == (byte)DUT_Number)
						{
							for (int j = num; j < 63; j++)
							{
								memoryMappedViewAccessor.Read<byte>(j + 1, out structure);
								memoryMappedViewAccessor.Write(j, structure);
							}
							memoryMappedViewAccessor.Write(63L, 0);
						}
						else
						{
							num++;
						}
					}
					return;
				}
				finally
				{
					mutex.ReleaseMutex();
				}
			}
			throw new Exception("Failed to remove DUT:" + DUT_Number + " from the Queue.");
		}
		catch (FileNotFoundException)
		{
		}
	}
}
