using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using QC.QTMInterface;

namespace QC.TestResultsLite;

internal class TestData
{
	public const string PARAM_LOOP_SEP = " _ ";

	public static string linkedRootName = "";

	public static bool showLinkedTreeNameCol = false;

	public static void GenerateData(MsgData msgData, DataTable testDT, ArrayList testerConfigList, bool showTestWithoutParams, out string strCurrUnitName)
	{
		strCurrUnitName = msgData.TestFullPath;
		string[] separator = new string[1] { " _ " };
		string[] separator2 = new string[1] { "_ _" };
		try
		{
			Hashtable hashUUT_SN = new Hashtable();
			ParseUUT_SN(msgData.SerialNumber, ref hashUUT_SN);
			ArrayList arrayList = (ArrayList)msgData.ParamResult;
			int newRID = 0;
			if (arrayList.Count > 0)
			{
				string text = "";
				{
					foreach (ParamValue item in arrayList)
					{
						if (item.ParamName.Contains(" _ "))
						{
							string[] array = item.ParamName.Split(separator, StringSplitOptions.None);
							if (text != array[1])
							{
								if (string.IsNullOrEmpty(msgData.LoopDetails))
								{
									msgData.LoopDetails = array[1].Trim();
								}
								else
								{
									string[] array2 = array[1].Split(separator2, StringSplitOptions.None);
									string[] array3 = array2;
									foreach (string text2 in array3)
									{
										if (!msgData.LoopDetails.Contains(text2.Trim()))
										{
											msgData.LoopDetails = msgData.LoopDetails + "_ _" + text2;
										}
									}
								}
								ParamValue p = item;
								p.ParamName = array[0].Trim();
								AddParam(msgData, testDT, testerConfigList, ref strCurrUnitName, hashUUT_SN, ref newRID, p);
							}
							else
							{
								ParamValue p2 = item;
								p2.ParamName = array[0].Trim();
								AddParam(msgData, testDT, testerConfigList, ref strCurrUnitName, hashUUT_SN, ref newRID, p2);
							}
						}
						else
						{
							AddParam(msgData, testDT, testerConfigList, ref strCurrUnitName, hashUUT_SN, ref newRID, item);
						}
					}
					return;
				}
			}
			if (showTestWithoutParams)
			{
				DataRow dataRow = testDT.NewRow();
				strCurrUnitName = GetSerialNumber(msgData, testerConfigList, hashUUT_SN, dataRow);
				dataRow["TestResult"] = msgData.Result;
				dataRow["TestName"] = msgData.TestFullPath;
				dataRow["SessionDataRID"] = newRID;
				dataRow["ScnValue"] = msgData.LoopDetails;
				testDT.Rows.Add(dataRow);
			}
		}
		catch (Exception ex)
		{
			throw new Exception("GenerateData failed, " + ex.Message);
		}
	}

	private static void AddParam(MsgData msgData, DataTable testDT, ArrayList testerConfigList, ref string strCurrUnitName, Hashtable hashUUT_SN, ref int newRID, ParamValue p)
	{
		int num = 0;
		for (int i = 0; i < p.Value.Count; i++)
		{
			if (!(bool)p.EnabledDataLogging[i])
			{
				continue;
			}
			try
			{
				num++;
				if (TestResultsLite.DataLoggingConfig.EnableVisibleArraySize && num > TestResultsLite.DataLoggingConfig.MaxVisibleArraySize)
				{
					break;
				}
				strCurrUnitName = AddRow(msgData, testDT, testerConfigList, hashUUT_SN, ref newRID, p, i);
			}
			catch (Exception ex)
			{
				throw new Exception("\n\non addding to Grid " + ex.Message);
			}
		}
	}

	private static string AddRow(MsgData msgData, DataTable testDT, ArrayList testerConfigList, Hashtable hashUUT_SN, ref int newRID, ParamValue p, int counter)
	{
		DataRow dataRow = testDT.NewRow();
		string serialNumber = GetSerialNumber(msgData, testerConfigList, hashUUT_SN, dataRow);
		dataRow["TestResult"] = msgData.Result;
		dataRow["ScnValue"] = msgData.LoopDetails;
		dataRow["TestName"] = msgData.TestFullPath;
		dataRow["SessionDataRID"] = newRID;
		newRID++;
		try
		{
			if (p.Value.Count > 1)
			{
				dataRow["ParameterName"] = p.ParamName + "::" + counter;
				AddArrayInfo(dataRow, p, counter);
			}
			else
			{
				dataRow["ParameterName"] = p.ParamName;
			}
			dataRow["Array Param Name"] = p.ParamName;
		}
		catch
		{
		}
		try
		{
			dataRow["UOM"] = p.Unit;
		}
		catch
		{
		}
		try
		{
			if (counter < p.LL.Count)
			{
				dataRow["LowerLimit"] = p.LL[counter];
			}
		}
		catch
		{
		}
		try
		{
			string text = Convert.ToString(p.Value[counter]);
			if (p.dataType != DataType.String && p.dataType != DataType.Boolean)
			{
				if (double.TryParse(text, out var result))
				{
					dataRow["NumValue"] = result;
				}
				else
				{
					if (p.DispHint == 8 && QsprUtility.GetParamEnumValueAsDouble(text, p.Constraint, out result))
					{
						dataRow["NumValue"] = result;
					}
					dataRow["CharValue"] = text;
				}
			}
			else
			{
				dataRow["CharValue"] = text;
			}
		}
		catch
		{
		}
		try
		{
			if (counter < p.UL.Count)
			{
				dataRow["UpperLimit"] = p.UL[counter];
			}
		}
		catch
		{
		}
		try
		{
			if (!string.IsNullOrEmpty(linkedRootName) && showLinkedTreeNameCol)
			{
				dataRow["LinkedTreeName"] = linkedRootName;
			}
		}
		catch
		{
		}
		try
		{
			if (p.dataType == DataType.Boolean)
			{
				bool.TryParse(dataRow["CharValue"].ToString(), out var result2);
				bool result3 = result2;
				bool result4 = result2;
				bool flag = bool.TryParse(dataRow["LowerLimit"].ToString(), out result3);
				bool flag2 = bool.TryParse(dataRow["UpperLimit"].ToString(), out result4);
				if ((flag && result3 != result2) || (flag2 && result4 != result2))
				{
					dataRow["ParamResult"] = TestResult.Failed;
				}
				else
				{
					dataRow["ParamResult"] = TestResult.Passed;
				}
			}
			else if (p.dataType != DataType.String && p.dataType != DataType.Boolean)
			{
				double result5;
				bool flag3 = double.TryParse(dataRow["LowerLimit"].ToString(), out result5);
				double result6;
				bool flag4 = double.TryParse(dataRow["UpperLimit"].ToString(), out result6);
				double.TryParse(dataRow["NumValue"].ToString(), out var result7);
				if ((flag3 && result5 > result7) || (flag4 && result7 > result6))
				{
					dataRow["ParamResult"] = TestResult.Failed;
				}
				else
				{
					dataRow["ParamResult"] = TestResult.Passed;
				}
			}
			else if (p.dataType == DataType.String)
			{
				string text2 = dataRow["LowerLimit"].ToString();
				string text3 = dataRow["UpperLimit"].ToString();
				string strB = dataRow["CharValue"].ToString();
				if (string.IsNullOrEmpty(text2.Trim()) && string.IsNullOrEmpty(text3.Trim()))
				{
					dataRow["ParamResult"] = TestResult.Passed;
				}
				else if (text2.CompareTo(strB) == 0 && text3.CompareTo(strB) == 0)
				{
					dataRow["ParamResult"] = TestResult.Passed;
				}
				else
				{
					dataRow["ParamResult"] = TestResult.Failed;
				}
			}
			else
			{
				dataRow["ParamResult"] = TestResult.Passed;
			}
		}
		catch
		{
		}
		finally
		{
			if (string.IsNullOrEmpty(dataRow["ParamResult"].ToString()))
			{
				dataRow["ParamResult"] = msgData.Result;
			}
		}
		testDT.Rows.Add(dataRow);
		return serialNumber;
	}

	private static void AddArrayInfo(DataRow row, ParamValue p, int counter)
	{
		try
		{
			row["ArrayParamIndex"] = counter;
			try
			{
				if (counter < p.LL.Count)
				{
					row["LowerLimit"] = p.LL[counter];
				}
			}
			catch
			{
			}
			try
			{
				string text = Convert.ToString(p.Value[counter]);
				if (p.dataType != DataType.String && p.dataType != DataType.Boolean)
				{
					if (double.TryParse(text, out var result))
					{
						row["ArrayResult"] = result;
					}
					else
					{
						row["ArrayParamCharResult"] = text;
					}
				}
				else
				{
					row["ArrayParamCharResult"] = text;
				}
			}
			catch
			{
			}
			try
			{
				if (counter < p.UL.Count)
				{
					row["ArrayUpperLimit"] = p.UL[counter];
				}
			}
			catch
			{
			}
		}
		catch (Exception ex)
		{
			TraceWriter.WriteLine("AddArrayInfo failed, " + ex.Message, "Exception");
		}
	}

	public static string GetSerialNumber(MsgData msgData, ArrayList testerConfigList, Hashtable hashUUT_SN, DataRow row)
	{
		if (TestResultsLite.TesterConfigHasSerialNumber)
		{
			string partOfUnitIDNameValuePairs = GetPartOfUnitIDNameValuePairs(testerConfigList);
			string[] array = partOfUnitIDNameValuePairs.Split(new string[1] { "_ _" }, StringSplitOptions.RemoveEmptyEntries);
			string[] array2 = array;
			foreach (string text in array2)
			{
				try
				{
					string[] array3 = text.Split(new string[1] { "__" }, StringSplitOptions.RemoveEmptyEntries);
					row[array3[0]] = array3[1];
				}
				catch
				{
				}
			}
		}
		else if (msgData.UnitIndex == 0 && hashUUT_SN.Count > 1)
		{
			row["UUT_SN"] = "All Units";
		}
		else if (msgData.UnitIndex == 0)
		{
			row["UUT_SN"] = msgData.SerialNumber;
		}
		else
		{
			try
			{
				if (hashUUT_SN.ContainsKey(msgData.UnitIndex))
				{
					row["UUT_SN"] = (string)hashUUT_SN[msgData.UnitIndex];
				}
			}
			catch
			{
			}
		}
		return row["UUT_SN"].ToString();
	}

	private static string GetPartOfUnitIDNameValuePairs(ArrayList configList)
	{
		try
		{
			string text = "";
			foreach (TesterConfigurationInfo config in configList)
			{
				if (config.PartOfUnitID)
				{
					if (text != "")
					{
						text += "_ _";
					}
					text = text + config.Name + "__" + config.Value;
				}
			}
			return text;
		}
		catch (Exception ex)
		{
			throw new Exception("GetPartOfUnitIDNameValuePairs failed, " + ex.Message);
		}
	}

	private static void ParseUUT_SN(string uut_SN, ref Hashtable hashUUT_SN)
	{
		try
		{
			hashUUT_SN = new Hashtable();
			if (uut_SN.Contains("%^&"))
			{
				string[] array = uut_SN.Split(new string[1] { "%^&" }, StringSplitOptions.RemoveEmptyEntries);
				for (int i = 1; i <= array.Length; i++)
				{
					hashUUT_SN.Add(i, array[i - 1]);
				}
			}
			else
			{
				hashUUT_SN.Add(1, uut_SN);
			}
		}
		catch (Exception ex)
		{
			throw new Exception("ParseUUT_SN failed, " + ex.Message);
		}
	}

	public static void WriteDataToFile(object data, string fileName)
	{
		try
		{
			if (data != null)
			{
				FileStream fileStream = new FileStream(fileName, FileMode.Create);
				using (fileStream)
				{
					BinaryFormatter binaryFormatter = new BinaryFormatter();
					binaryFormatter.Serialize(fileStream, data);
					fileStream.Close();
					return;
				}
			}
		}
		catch
		{
		}
	}

	public static object ReadDataFromFile(string fileName)
	{
		object result = new object();
		try
		{
			if (!File.Exists(fileName))
			{
				throw new Exception("Intermediate file: " + fileName + " is missing");
			}
			FileStream fileStream = new FileStream(fileName, FileMode.Open);
			using (fileStream)
			{
				BinaryFormatter binaryFormatter = new BinaryFormatter();
				result = binaryFormatter.Deserialize(fileStream);
				fileStream.Close();
			}
		}
		catch
		{
		}
		return result;
	}
}
