using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Serialization;
using QC.QTMDotNetKernelInterface;
using QC.QTMDotNetKernelInterface.Environment;

namespace QC.MultiplexManager;

[QTMTestClass]
public class MultiDutUtils : QSPRTest
{
	private string[] csvAllRows;

	private int currRow;

	private ConfigurationFile cfg;

	private ConfigurationFile CfgFile
	{
		get
		{
			return cfg;
		}
		set
		{
			cfg = value;
		}
	}

	public MultiDutUtils(QSPREnvironment qsprEnv)
		: base(qsprEnv)
	{
	}

	[QTMTest(Description = "Get data in MM file to format a CSV file", CanAddToTestPlan = true)]
	public bool CreateCSVFile()
	{
		try
		{
			string gvValue = "";
			base.Env.GlobalVariable.GetGlobalVariable("MULTIPLEX_MANAGER_CONFIG_FILE", out gvValue);
			if (!File.Exists(gvValue))
			{
				gvValue = "C:\\Program Files (x86)\\Qualcomm\\QDART\\Databases\\MultiplexManagerConfigFile.xml";
				if (!File.Exists(gvValue))
				{
					gvValue = "C:\\Program Files\\Qualcomm\\QDART\\Databases\\MultiplexManagerConfigFile.xml";
					if (!File.Exists(gvValue))
					{
						base.Env.DebugMessage.Write("Error", "Not found Databases\\MultiplexManagerConfigFile.xml");
						return false;
					}
				}
				base.Env.GlobalVariable.SetGlobalVariable("MULTIPLEX_MANAGER_CONFIG_FILE", gvValue);
			}
			DeserializeConfigFile(gvValue);
			if (!CfgFile.MultiDUTConfigItems.MultiplexersSection.MultiplexerList[0].DriverDLL.Contains("MCI_QTI_SCPI.dll"))
			{
				base.Env.DebugMessage.Write("Error", "MultiplexManagerConfigFile.xml not found MCI_QTI_SCPI.dll configured");
				base.Env.DebugMessage.Write("Debug", "MultiplexManagerConfigFile.xml not found MCI_QTI_SCPI.dll configured");
				return false;
			}
			DataTable dataTable = new DataTable();
			dataTable.Columns.Add("INDEX", Type.GetType("System.String"));
			dataTable.Columns.Add("DUT_INDEX", Type.GetType("System.String"));
			dataTable.Columns.Add("GSM", Type.GetType("System.String"));
			dataTable.Columns.Add("CDMA", Type.GetType("System.String"));
			dataTable.Columns.Add("WCDMA", Type.GetType("System.String"));
			dataTable.Columns.Add("TDSCDMA", Type.GetType("System.String"));
			dataTable.Columns.Add("LTE", Type.GetType("System.String"));
			dataTable.Columns.Add("PORT_STRING", Type.GetType("System.String"));
			dataTable.Columns.Add("CALDB_TX_PATH_ID", Type.GetType("System.String"));
			dataTable.Columns.Add("CALDB_RX_PATH_ID", Type.GetType("System.String"));
			dataTable.Columns.Add("CALDB_TX_CONFIG_NAME", Type.GetType("System.String"));
			dataTable.Columns.Add("CALDB_RX_CONFIG_NAME", Type.GetType("System.String"));
			dataTable.Columns.Add("PORTS", Type.GetType("System.String"));
			dataTable.Columns.Add("MULTIPLEXER", Type.GetType("System.String"));
			dataTable.Columns.Add("BANDS", Type.GetType("System.String"));
			dataTable.Columns.Add("FTMRFTestSupported", Type.GetType("System.String"));
			int num = 0;
			ROUTING_CONFIG[] routingList = CfgFile.MultiDUTConfigItems.MultiplexersSection.MultiplexerList[0].RoutingList;
			foreach (ROUTING_CONFIG rOUTING_CONFIG in routingList)
			{
				string[] array = FormatString4CSV(rOUTING_CONFIG.Routing_Config).Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
				int num2 = array.Length;
				if (num2 < 1)
				{
					return false;
				}
				for (int j = 0; j < num2; j++)
				{
					DataRow dataRow = dataTable.NewRow();
					num++;
					dataRow["INDEX"] = num.ToString();
					dataRow["DUT_INDEX"] = (j + 1).ToString();
					if (!rOUTING_CONFIG.Ports.Contains("WWAN_ANT"))
					{
						dataRow["GSM"] = (rOUTING_CONFIG.Ports.Contains("GSM") ? "1" : "0");
						dataRow["CDMA"] = (rOUTING_CONFIG.Ports.Contains("CDMA") ? "1" : "0");
						dataRow["WCDMA"] = (rOUTING_CONFIG.Ports.Contains("WCDMA") ? "1" : "0");
						dataRow["TDSCDMA"] = (rOUTING_CONFIG.Ports.Contains("TDSCDMA") ? "1" : "0");
						dataRow["LTE"] = (rOUTING_CONFIG.Ports.Contains("LTE") ? "1" : "0");
					}
					else
					{
						dataRow["GSM"] = "1";
						dataRow["CDMA"] = "1";
						dataRow["WCDMA"] = "1";
						dataRow["TDSCDMA"] = "1";
						dataRow["LTE"] = "1";
					}
					dataRow["PORT_STRING"] = array[j];
					dataRow["CALDB_TX_PATH_ID"] = rOUTING_CONFIG.Tx_Cal_Path_Number;
					dataRow["CALDB_RX_PATH_ID"] = rOUTING_CONFIG.Rx_Cal_Path_Number;
					dataRow["CALDB_TX_CONFIG_NAME"] = FormatString4CSV(rOUTING_CONFIG.Tx_Cal_Path_Config_Name);
					dataRow["CALDB_RX_CONFIG_NAME"] = FormatString4CSV(rOUTING_CONFIG.Rx_Cal_Path_Config_Name);
					dataRow["PORTS"] = rOUTING_CONFIG.Ports;
					dataRow["MULTIPLEXER"] = "1";
					dataRow["BANDS"] = FormatString4CSV(rOUTING_CONFIG.Bands);
					dataRow["FTMRFTestSupported"] = (rOUTING_CONFIG.Ports.Contains("WWAN_ANT") ? "1" : "0");
					if (!rOUTING_CONFIG.Ports.Contains("BT") && !rOUTING_CONFIG.Ports.Contains("WLAN") && !rOUTING_CONFIG.Ports.Contains("GNSS"))
					{
						dataTable.Rows.Add(dataRow);
					}
				}
			}
			CreateACSVFile(dataTable, "C:\\qualcomm\\mm.csv", includeColNames: true);
			return true;
		}
		catch (Exception ex)
		{
			base.Env.DebugMessage.Write("Error", "Exception: " + ex.Message);
			return false;
		}
	}

	[QTMTest(Description = "Opens a CSVFile and keeps the contents available for further reading for other tests", CanAddToTestPlan = true)]
	public bool ReadCSVFile(bool skipHeader)
	{
		try
		{
			csvAllRows = File.ReadAllLines("C:\\qualcomm\\mm.csv");
			currRow = 0;
			if (skipHeader)
			{
				currRow = 1;
			}
			if (csvAllRows.Length < 2)
			{
				base.Env.DebugMessage.Write("Error", "CSV file lack wanted information.");
				return false;
			}
			return true;
		}
		catch (Exception ex)
		{
			base.Env.DebugMessage.Write("Error", ex.Message);
			return false;
		}
	}

	[QTMTest(Description = "Call ReadCSVFile test first.", CanAddToTestPlan = true)]
	public bool GetNextRowData(bool gotoNextRow, out string data, out bool nextRowAvilable)
	{
		data = "";
		string text = "";
		nextRowAvilable = false;
		try
		{
			if (csvAllRows == null)
			{
				text = "Make sure there is a CSV file open using ReadCSVFile test";
				return false;
			}
			if (csvAllRows.GetLength(0) > currRow)
			{
				string[] array = SplitCSVWithQuotes(csvAllRows[currRow]);
				base.Env.DebugMessage.Write("Log", csvAllRows[currRow], TraceLevel.Verbose);
				if (gotoNextRow)
				{
					currRow++;
				}
				if (array.Length > 15)
				{
					base.Env.GlobalVariable.SetGlobalVariable("INDEX", array[0]);
					base.Env.GlobalVariable.SetGlobalVariable("DUT_INDEX", array[1]);
					base.Env.GlobalVariable.SetGlobalVariable("GSM", array[2]);
					base.Env.GlobalVariable.SetGlobalVariable("CDMA", array[3]);
					base.Env.GlobalVariable.SetGlobalVariable("WCDMA", array[4]);
					base.Env.GlobalVariable.SetGlobalVariable("TDSCDMA", array[5]);
					base.Env.GlobalVariable.SetGlobalVariable("LTE", array[6]);
					base.Env.GlobalVariable.SetGlobalVariable("PORT_STRING", array[7]);
					base.Env.GlobalVariable.SetGlobalVariable("CALDB_TX_PATH_ID", array[8]);
					base.Env.GlobalVariable.SetGlobalVariable("CALDB_RX_PATH_ID", array[9]);
					base.Env.GlobalVariable.SetGlobalVariable("CALDB_TX_CONFIG_NAME", array[10]);
					base.Env.GlobalVariable.SetGlobalVariable("CALDB_RX_CONFIG_NAME", array[11]);
					base.Env.GlobalVariable.SetGlobalVariable("PORTS", array[12]);
					base.Env.GlobalVariable.SetGlobalVariable("MULTIPLEXER", array[13]);
					base.Env.GlobalVariable.SetGlobalVariable("BANDS", array[14]);
					base.Env.GlobalVariable.SetGlobalVariable("FTMRFTestSupported", array[15]);
					Thread.Sleep(200);
				}
				if (csvAllRows.GetLength(0) > currRow)
				{
					nextRowAvilable = true;
				}
			}
			else
			{
				text = "Data not available for the given row.";
				base.Env.DebugMessage.Write("Debug", text);
			}
			return true;
		}
		catch (Exception ex)
		{
			base.Env.DebugMessage.Write("Debug", ex.Message);
			return false;
		}
	}

	[QTMTest(Description = "Branch in loop usage, do nothing", CanAddToTestPlan = true)]
	public bool BranchNode()
	{
		return true;
	}

	private string FormatString4CSV(string inPara)
	{
		inPara = inPara.Trim().Replace("\r", "").Replace("\n", "")
			.Replace("\t", "");
		if (string.IsNullOrEmpty(inPara))
		{
			inPara = "DONTCARE";
		}
		return inPara;
	}

	private void DeserializeConfigFile(string configFileName)
	{
		CfgFile = null;
		try
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(ConfigurationFile));
			FileStream fileStream = new FileStream(configFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
			CfgFile = (ConfigurationFile)xmlSerializer.Deserialize(fileStream);
			fileStream.Close();
			fileStream = null;
			if (CfgFile == null)
			{
				throw new Exception("Deserialization of " + configFileName + "failed!\n");
			}
			base.Env.DebugMessage.Write("Debug", "Multiplex Manager Config File: " + configFileName);
		}
		catch (Exception ex)
		{
			CfgFile = null;
			throw ex;
		}
	}

	private bool CreateACSVFile(DataTable dataTable, string csvFileName, bool includeColNames)
	{
		if (dataTable == null)
		{
			return false;
		}
		try
		{
			base.Env.DebugMessage.Write("Debug", " Column count " + dataTable.Columns.Count);
			StreamWriter streamWriter = File.CreateText(csvFileName);
			int count = dataTable.Columns.Count;
			if (includeColNames)
			{
				for (int i = 0; i < count - 1; i++)
				{
					streamWriter.Write(dataTable.Columns[i].ColumnName + ",");
				}
				streamWriter.Write(dataTable.Columns[count - 1].ColumnName + "\r\n");
			}
			foreach (DataRow row in dataTable.Rows)
			{
				string text;
				for (int j = 0; j < count - 1; j++)
				{
					text = row[j].ToString();
					if (text.Contains(",") || text.Contains(":"))
					{
						text = "\"" + text + "\"";
					}
					streamWriter.Write(text + ",");
				}
				text = row[count - 1].ToString();
				if (text.Contains(","))
				{
					text = "\"" + text + "\"";
				}
				streamWriter.Write(text + "\r\n");
			}
			streamWriter.Flush();
			streamWriter.Close();
		}
		catch (Exception ex)
		{
			base.Env.DebugMessage.Write("Error", ex.Message);
			return false;
		}
		return true;
	}

	[QTMTest(Description = "Returns cell value from a CSV file based on Column name and row number (0 based index)", CanAddToTestPlan = false)]
	public bool GetCellValueUsingColumnName(string[] csvRows, string csvColumnName, int csvRowNo, out string csvCellValue)
	{
		csvCellValue = "";
		try
		{
			csvColumnName = csvColumnName.Trim();
			string[] array = SplitCSVWithQuotes(csvRows[0]);
			int num = 0;
			for (num = 0; num < array.Length && !(array[num] == csvColumnName); num++)
			{
			}
			if (num >= array.Length)
			{
				_ = "Column header " + csvColumnName + " not found";
				return false;
			}
			return GetCellValueFromStringArray(csvRows, num, csvRowNo, out csvCellValue);
		}
		catch (Exception ex)
		{
			_ = ex.Message;
			base.Env.DebugMessage.Write("GetCellValueFromHeaderFromCSVFile", ex.Message);
			return false;
		}
	}

	private string[] SplitCSVWithQuotes(string rowData)
	{
		Regex regex = new Regex("\"[^\"\\r\\n]*\"|'[^'\\r\\n]*'|[^,\\r\\n]*");
		Match match = regex.Match(rowData);
		ArrayList arrayList = new ArrayList();
		string text = "'\"";
		while (match.Success)
		{
			if (match.Value != string.Empty)
			{
				arrayList.Add(match.Value.Trim(text.ToCharArray()));
			}
			match = match.NextMatch();
		}
		string[] array = new string[arrayList.Count];
		for (int i = 0; i < arrayList.Count; i++)
		{
			array[i] = arrayList[i].ToString();
		}
		return array;
	}

	private bool GetCellValueFromStringArray(string[] rows, int colNo, int rowNo, out string cellValue)
	{
		cellValue = "";
		try
		{
			if (rows.Length < rowNo)
			{
				_ = "Row " + rowNo + " not found ";
				return false;
			}
			string[] array = SplitCSVWithQuotes(rows[rowNo]);
			if (array.Length <= colNo)
			{
				_ = "Column " + colNo + " not found ";
				return false;
			}
			cellValue = array[colNo];
		}
		catch (Exception ex)
		{
			_ = ex.Message;
			return false;
		}
		return true;
	}
}
