using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using QC.TestDataConvertor;

namespace QC.QTMXmlSchema;

[Serializable]
public class QTMFormatUnitData
{
	public enum Result
	{
		Failed,
		Passed,
		Exception,
		Running,
		Skipped,
		Blocked,
		IgnoreSession
	}

	public enum ExtendedDataType
	{
		Yes,
		No,
		Maybe,
		Skip
	}

	public const string STYLE_SHEET_NAME = "QTMData.xsl";

	public const string STYLE_SHEET_PATH = "C:\\Qualcomm\\QSPR\\StyleSheets";

	public const string DEFAULT_FILE_PATH = "C:\\Qualcomm\\QSPR\\TestLog\\";

	public const string SESSION_DATA_SEP = "_ _";

	public const string SESSION_NAME_VALUE_SEP = "__";

	public const string TIMESTAMP_FORMAT = "M/d/yy HH:mm:ss:fff";

	public const string DURATION_FORMAT = "c";

	public CultureInfo _stringFormatProvider = CultureInfo.InvariantCulture;

	public bool Dirty = true;

	private Test currTest;

	private configInfo myConfig;

	private bool isLinkedTree;

	private ArrayList testColl;

	public Dictionary<string, string> additionalConfigTags = new Dictionary<string, string>();

	private string styleSheetName = "QTMData.xsl";

	private string styleSheetPath = "C:\\Qualcomm\\QSPR\\StyleSheets";

	private CSVColumnNames columnNames;

	public int LastRowWritten = -1;

	public configInfo Config
	{
		get
		{
			return myConfig;
		}
		set
		{
			myConfig = value;
		}
	}

	public bool IsLinkedTree
	{
		get
		{
			return isLinkedTree;
		}
		set
		{
			isLinkedTree = value;
		}
	}

	[XmlElement(Type = typeof(Test))]
	public ArrayList Tests
	{
		get
		{
			return testColl;
		}
		set
		{
			testColl = value;
		}
	}

	public string StyleSheetName
	{
		get
		{
			return styleSheetName;
		}
		set
		{
			styleSheetName = value;
		}
	}

	public string StyleSheetPath
	{
		get
		{
			return styleSheetPath;
		}
		set
		{
			styleSheetPath = value;
		}
	}

	public CSVColumnNames CSVColumnNames
	{
		get
		{
			return columnNames;
		}
		set
		{
			columnNames = value;
		}
	}

	public Test AddTest(string testName, Result testResult, string testIndex, TimeSpan testDuration, string errorCode, bool? limitsEnforced = null)
	{
		try
		{
			if (Tests == null)
			{
				Tests = new ArrayList();
			}
			Test test = new Test();
			test.TestName = testName;
			test.TestResult = testResult.ToString();
			test.NodeIndex = testIndex;
			test.TestDuration = testDuration;
			test.ErrorCode = errorCode;
			Tests.Add(test);
			currTest = test;
			Dirty = true;
			return test;
		}
		catch (Exception ex)
		{
			throw new Exception("AddTest failed for Test: " + testName + "; Error: " + ex.Message);
		}
	}

	public Test AddTest(string testName, Result testResult, string testIndex, TimeSpan testDuration, string errorCode, bool isLinkedTree, List<string> linkedFiles, bool? limitsEnforced = null)
	{
		try
		{
			Test test = AddTest(testName, testResult, testIndex, testDuration, errorCode);
			test.IsLinkedTree = isLinkedTree;
			test.LinkedFiles = linkedFiles;
			return test;
		}
		catch (Exception ex)
		{
			throw new Exception("AddTest failed for Test: " + testName + "; Error: " + ex.Message);
		}
	}

	public Test AddTest(string testName, Result testResult, string testIndex, DateTime testStartTime, DateTime testStopTime, TimeSpan testDuration, string errorCode, int testCaseId, int testCaseRefId, string testComments, string logFilePath, string jiraId, string crId, string warning, string errorDesc, string irID, string srID, string jiraCategories, bool? limitsEnforced = null)
	{
		try
		{
			if (Tests == null)
			{
				Tests = new ArrayList();
			}
			Test test = new Test();
			test.TestName = testName;
			test.TestResult = testResult.ToString();
			test.NodeIndex = testIndex;
			test.TestStartTime = testStartTime.ToString("M/d/yy HH:mm:ss:fff");
			test.TestStopTime = testStopTime.ToString("M/d/yy HH:mm:ss:fff");
			test.TestDuration = testDuration;
			test.ErrorCode = errorCode;
			test.TestCaseRID = testCaseId;
			test.TestCaseRefRID = testCaseRefId;
			test.Comments = testComments;
			test.LogFilePath = logFilePath;
			test.JIRAID = jiraId;
			test.CRID = crId;
			test.Warning = warning;
			test.ErrorDesc = errorDesc;
			test.IRID = irID;
			test.SRID = srID;
			test.JIRACategories = jiraCategories;
			Tests.Add(test);
			currTest = test;
			Dirty = true;
			return test;
		}
		catch (Exception ex)
		{
			throw new Exception("AddTest failed for Test: " + testName + "; Error: " + ex.Message);
		}
	}

	public void AddParamToCurrentTest(string paramName, string unitOfMeasure, string charValue, string extHyperLink, bool? reportingEnabled = null, string dataType = null)
	{
		try
		{
			if (currTest != null)
			{
				currTest.AddParameter(paramName, unitOfMeasure, charValue, extHyperLink, reportingEnabled);
				return;
			}
			throw new Exception("Current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddParamToCurrentTest " + paramName + " failed; Error " + ex.Message);
		}
	}

	public void AddParamToCurrentTest(string paramName, string unitOfMeasure, string charValue, string dataType = null)
	{
		AddParamToCurrentTest(paramName, unitOfMeasure, charValue, (bool?)null, dataType);
	}

	public void AddParamToCurrentTest(string paramName, string unitOfMeasure, string charValue, bool? reportingEnabled, string dataType = null)
	{
		try
		{
			if (currTest != null)
			{
				currTest.AddParameter(paramName, unitOfMeasure, charValue, reportingEnabled);
				return;
			}
			throw new Exception("Current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddParamToCurrentTest " + paramName + " failed; Error " + ex.Message);
		}
	}

	public void AddParamToCurrentTest(string paramName, string unitOfMeasure, string charValue, string upperLimit, string lowerLimit, string dataType = null)
	{
		try
		{
			if (currTest != null)
			{
				currTest.AddParameter(paramName, unitOfMeasure, charValue, null, upperLimit, lowerLimit, dataType);
				return;
			}
			throw new Exception("Current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddParamToCurrentTest " + paramName + " failed; Error " + ex.Message);
		}
	}

	public void AddParamToCurrentTest(string paramName, string unitOfMeasure, double? paramValue, string upperLimit, string lowerLimit, bool? reportingEnabled = null, string dataType = null)
	{
		try
		{
			if (currTest != null)
			{
				currTest.AddParameter(paramName, unitOfMeasure, paramValue, upperLimit, lowerLimit, reportingEnabled, dataType);
				return;
			}
			throw new Exception("Current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddParamToCurrentTest " + paramName + " failed; Error " + ex.Message);
		}
	}

	public void AddTestCaseDataToCurrentTest(DateTime testStartTime, DateTime testStopTime, int testCaseId, int testCaseRefId, string testComments, string logFilePath, string jiraId, string crId, string warning, string errorDesc)
	{
		if (currTest != null)
		{
			currTest.TestStartTime = testStartTime.ToString("M/d/yy HH:mm:ss:fff");
			currTest.TestStopTime = testStopTime.ToString("M/d/yy HH:mm:ss:fff");
			currTest.TestCaseRID = testCaseId;
			currTest.TestCaseRefRID = testCaseRefId;
			currTest.Comments = testComments;
			currTest.LogFilePath = logFilePath;
			currTest.JIRAID = jiraId;
			currTest.CRID = crId;
			currTest.Warning = warning;
			currTest.ErrorDesc = errorDesc;
			return;
		}
		throw new Exception("Current Test is null");
	}

	public void AddLoopConditionsToCurrentTest(string loopName, string loopValue)
	{
		AddLoopConditionsToCurrentTest(loopName, loopValue, isInputParam: false);
	}

	public void AddLoopConditionsToCurrentTest(string loopName, string loopValue, bool isInputParam)
	{
		try
		{
			if (currTest != null)
			{
				currTest.AddLoopCondition(loopName, loopValue, isInputParam);
				return;
			}
			throw new Exception("Current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddLoopConditionsToCurrentTest for LoopName " + loopName + " failed, Error: " + ex.Message);
		}
	}

	public void AddArrayItemToCurrParam(string arrayItemName, string arrayItemIndex, string arrayItemColIndex, string arrayItemCharValue, string arrayItemExtHyperLink)
	{
		try
		{
			if (currTest != null && currTest.currParam != null)
			{
				currTest.currParam.AddArrayItem(arrayItemName, arrayItemIndex, arrayItemColIndex, arrayItemCharValue, arrayItemExtHyperLink);
				return;
			}
			throw new Exception("Current Parameter of current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddArrayItemToCurrParam " + arrayItemName + " failed, Error:" + ex.Message);
		}
	}

	public void AddArrayItemToCurrParam(string arrayItemName, string arrayItemIndex, string arrayItemColIndex, string arrayItemCharValue)
	{
		try
		{
			if (currTest != null && currTest.currParam != null)
			{
				currTest.currParam.AddArrayItem(arrayItemName, arrayItemIndex, arrayItemColIndex, arrayItemCharValue);
				return;
			}
			throw new Exception("Current Parameter of current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddArrayItemToCurrParam " + arrayItemName + " failed, Error:" + ex.Message);
		}
	}

	public void AddAdditionlInfoToCurrentParam(string key, string value)
	{
		try
		{
			if (currTest != null && currTest.currParam != null)
			{
				currTest.currParam.AdditionalInfo(key, value);
				return;
			}
			throw new Exception("Current Parameter of current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddAdditionlInfoToCurrentParam " + currTest.TestName + " " + currTest.currParam.Name + " failed, Error:" + ex.Message);
		}
	}

	public void AddParamResultsToCurrentParam(bool paramResult)
	{
		try
		{
			if (currTest != null && currTest.currParam != null)
			{
				currTest.currParam.Result = paramResult;
				return;
			}
			throw new Exception("Current Parameter of current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddParamResultsToCurrentParam " + currTest.TestName + " " + currTest.currParam.Name + " failed, Error:" + ex.Message);
		}
	}

	public void AddArrayItemToCurrParam(string arrayItemName, string arrayItemIndex, string arrayItemColIndex, double? arrayItemValue, string arrayItemUpperLimit, string arrayItemLowerLimit)
	{
		try
		{
			if (currTest != null && currTest.currParam != null)
			{
				currTest.currParam.AddArrayItem(arrayItemName, arrayItemIndex, arrayItemColIndex, arrayItemValue, arrayItemUpperLimit, arrayItemLowerLimit);
				return;
			}
			throw new Exception("Current Parameter of current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddArrayItemToCurrParam " + arrayItemName + " failed, Error:" + ex.Message);
		}
	}

	public void AddArrayItemToCurrParam(string arrayItemName, string arrayItemIndex, string arrayItemColIndex, string arrayItemValue, string arrayItemUpperLimit, string arrayItemLowerLimit)
	{
		try
		{
			if (currTest != null && currTest.currParam != null)
			{
				currTest.currParam.AddArrayItem(arrayItemName, arrayItemIndex, arrayItemColIndex, arrayItemValue, arrayItemUpperLimit, arrayItemLowerLimit);
				return;
			}
			throw new Exception("Current Parameter of current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddArrayItemToCurrParam " + arrayItemName + " failed, Error:" + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, DateTime startTime, DateTime stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode, string treeFileName, string treeType, string computerName, string registeredMachine, string software_MCN, string hardware_version, string software_version, string siteKey, string database, string server, string siteTreeId, List<string> linkedFiles, string tpByVerRID)
	{
		try
		{
			if (tpByVerRID != string.Empty)
			{
				Config.TPByVersionRID = tpByVerRID;
			}
			AddStandardConfig(serialNo, treeResult, startTime, stopTime, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, treeFileName, treeType, computerName, registeredMachine, software_MCN, hardware_version, software_version, siteKey, database, server, siteTreeId, linkedFiles);
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, string startTime, string stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode, string treeFileName, string treeType, string computerName, string registeredMachine, string software_MCN, string hardware_version, string software_version, string siteKey, string database, string server, string siteTreeId, string tpByVerRID)
	{
		try
		{
			if (tpByVerRID != string.Empty)
			{
				Config.TPByVersionRID = tpByVerRID;
			}
			AddStandardConfigData(serialNo, treeResult, startTime, stopTime, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, treeFileName, treeType, computerName, registeredMachine, software_MCN, hardware_version, software_version, siteKey, database, server, siteTreeId, new List<string>());
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, string startTime, string stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode, string treeFileName, string treeType, string computerName, string registeredMachine, string software_MCN, string hardware_version, string software_version, string siteKey, string database, string server, string siteTreeId)
	{
		try
		{
			AddStandardConfigData(serialNo, treeResult, startTime, stopTime, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, treeFileName, treeType, computerName, registeredMachine, software_MCN, hardware_version, software_version, siteKey, database, server, siteTreeId, new List<string>());
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, DateTime startTime, DateTime stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode, string treeFileName, string treeType, string computerName, string registeredMachine, string software_MCN, string hardware_version, string software_version, string siteKey, string database, string server, string siteTreeId)
	{
		try
		{
			string startTime2 = RoundDateTimeToNearestMilliSecond(startTime).ToString("M/d/yy HH:mm:ss:fff");
			string stopTime2 = RoundDateTimeToNearestMilliSecond(stopTime).ToString("M/d/yy HH:mm:ss:fff");
			AddStandardConfigData(serialNo, treeResult, startTime2, stopTime2, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, treeFileName, treeType, computerName, registeredMachine, software_MCN, hardware_version, software_version, siteKey, database, server, siteTreeId, new List<string>());
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, DateTime startTime, DateTime stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode, string treeFileName, string treeType, string computerName, string registeredMachine, string software_MCN, string hardware_version, string software_version, string siteKey, string database, string server, string siteTreeId, List<string> linkedFiles)
	{
		try
		{
			string startTime2 = RoundDateTimeToNearestMilliSecond(startTime).ToString("M/d/yy HH:mm:ss:fff");
			string stopTime2 = RoundDateTimeToNearestMilliSecond(stopTime).ToString("M/d/yy HH:mm:ss:fff");
			AddStandardConfigData(serialNo, treeResult, startTime2, stopTime2, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, treeFileName, treeType, computerName, registeredMachine, software_MCN, hardware_version, software_version, siteKey, database, server, siteTreeId, linkedFiles);
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, string startTime, string stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode)
	{
		try
		{
			AddStandardConfigData(serialNo, treeResult, startTime, stopTime, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, "", "", "", "", "", "", "", "", "", "", "", new List<string>());
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	public void AddStandardConfig(string serialNo, Result treeResult, DateTime startTime, DateTime stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode)
	{
		try
		{
			string startTime2 = RoundDateTimeToNearestMilliSecond(startTime).ToString("M/d/yy HH:mm:ss:fff");
			string stopTime2 = RoundDateTimeToNearestMilliSecond(stopTime).ToString("M/d/yy HH:mm:ss:fff");
			AddStandardConfigData(serialNo, treeResult, startTime2, stopTime2, testerId, treeId, workStation, MCN, comments, extendedData, errorCode, "", "", "", "", "", "", "", "", "", "", "", new List<string>());
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig failed, " + ex.Message);
		}
	}

	private void AddStandardConfigData(string serialNo, Result treeResult, string startTime, string stopTime, string testerId, string treeId, string workStation, string MCN, string comments, ExtendedDataType extendedData, string errorCode, string treeFileName, string treeType, string computerName, string registeredMachine, string Software_MCN, string hardware_version, string software_version, string siteKey, string database, string server, string siteTreeId, List<string> linkedFiles)
	{
		try
		{
			if (Config == null)
			{
				Config = new configInfo();
			}
			Config.UUT_SN = serialNo;
			Config.Result = treeResult.ToString();
			Config.TreeID = treeId;
			Config.StartTime = startTime;
			Config.StopTime = stopTime;
			Config.MachineName = computerName;
			Config.MCN = MCN;
			Config.SW_MCN = Software_MCN;
			Config.WORKSTATION = workStation;
			Config.TESTERID = testerId;
			Config.HW_VER = hardware_version;
			Config.SW_VER = software_version;
			Config.SiteKey = siteKey;
			Config.Database = database;
			Config.Server = server;
			Config.TreeFileName = treeFileName;
			Config.RegisteredMachine = registeredMachine;
			Config.TreeType = treeType;
			Config.SiteTreeID = siteTreeId;
			Config.Comments = comments;
			Config.ExtendedData = extendedData;
			Config.ErrorCode = errorCode;
			Config.LinkedFileNames = linkedFiles;
			DateTime result2;
			if (DateTime.TryParse(startTime, out var result))
			{
				if (DateTime.TryParse(stopTime, out result2))
				{
					Config.Duration = (result2 - result).ToString("c");
				}
			}
			else if (DateTime.TryParseExact(startTime, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result) && DateTime.TryParseExact(stopTime, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result2))
			{
				Config.Duration = (result2 - result).ToString("c");
			}
		}
		catch (Exception ex)
		{
			throw new Exception(ex.Message);
		}
	}

	public void AddConfig(string configName, string configValue)
	{
		try
		{
			if (Config == null)
			{
				Config = new configInfo();
			}
			if (Config.RunTitleTesterConfig == null)
			{
				Config.RunTitleTesterConfig = new Dictionary<string, string>();
			}
			if (Config.RunTitleTesterConfig.ContainsKey(configName))
			{
				Config.RunTitleTesterConfig[configName] = configValue;
			}
			else
			{
				Config.RunTitleTesterConfig.Add(configName, configValue);
			}
		}
		catch (Exception ex)
		{
			throw new Exception("AddConfig for " + configName + " failed; Error: " + ex.Message);
		}
	}

	public void AddConfigTag(string tagName, string tagValue)
	{
		if (!additionalConfigTags.ContainsKey(tagName))
		{
			additionalConfigTags.Add(tagName, tagValue);
		}
	}

	public QTMFormatUnitData()
	{
		Config = new configInfo();
		Config.UUT_SN = "NA";
		Config.LinkedFileNames = new List<string>();
		IsLinkedTree = false;
	}

	private void WriteLinkedTreeInfo(XmlTextWriter writer, List<string> linkedFiles)
	{
		try
		{
			if (linkedFiles == null || linkedFiles.Count <= 0)
			{
				return;
			}
			writer.WriteStartElement("LinkedTrees");
			foreach (string linkedFile in linkedFiles)
			{
				writer.WriteElementString("File", linkedFile);
			}
			writer.WriteEndElement();
		}
		catch (Exception ex)
		{
			throw new Exception("WriteLinkedFiles failed, Error: " + ex.Message);
		}
	}

	private void WriteLoop(XmlTextWriter writer, ArrayList loopConditions)
	{
		string text = "";
		try
		{
			if (loopConditions == null || loopConditions.Count <= 0)
			{
				return;
			}
			writer.WriteStartElement("Inputs");
			foreach (LoopCondition loopCondition in loopConditions)
			{
				if (text.Length != 0)
				{
					text += "_ _";
				}
				text = text + loopCondition.Key + "__" + loopCondition.Value;
				writer.WriteStartElement("Input");
				if (loopCondition.IsInputParam)
				{
					writer.WriteAttributeString("Type", "I");
				}
				else
				{
					writer.WriteAttributeString("Type", "L");
				}
				writer.WriteElementString("Key", loopCondition.Key);
				writer.WriteElementString("Value", loopCondition.Value);
				writer.WriteEndElement();
			}
			writer.WriteEndElement();
			if (text != null && text != "")
			{
				writer.WriteStartElement("LOOPVALUES");
				writer.WriteStartElement("LV");
				writer.WriteElementString("V", text);
				writer.WriteEndElement();
				writer.WriteEndElement();
			}
		}
		catch (Exception ex)
		{
			throw new Exception("WriteLoop " + text + "failed, Error: " + ex.Message);
		}
	}

	private void WriteParamArray(XmlTextWriter writer, ArrayResult paramArrayInfo)
	{
		try
		{
			writer.WriteStartElement("Array");
			writer.WriteElementString("N", paramArrayInfo.Name);
			writer.WriteElementString("I", paramArrayInfo.RowIndex);
			if (paramArrayInfo.ColumnIndex != null && paramArrayInfo.ColumnIndex != "")
			{
				writer.WriteElementString("CI", paramArrayInfo.ColumnIndex);
			}
			if (paramArrayInfo.CHAR_Value != null && paramArrayInfo.CHAR_Value != "")
			{
				if (!string.IsNullOrWhiteSpace(paramArrayInfo.LowerLimit))
				{
					writer.WriteElementString("LL", paramArrayInfo.LowerLimit);
				}
				writer.WriteElementString("CHAR_V", RemoveInvalidXmlChars(paramArrayInfo.CHAR_Value));
				if (!string.IsNullOrWhiteSpace(paramArrayInfo.UpperLimit))
				{
					writer.WriteElementString("UL", paramArrayInfo.UpperLimit);
				}
				if (paramArrayInfo.ExtHyperLink != null && paramArrayInfo.ExtHyperLink != "")
				{
					writer.WriteElementString("ExtHyperLink", paramArrayInfo.ExtHyperLink);
				}
			}
			else
			{
				paramArrayInfo.LowerLimit = IsHexValueConvertToInt(paramArrayInfo.LowerLimit);
				paramArrayInfo.UpperLimit = IsHexValueConvertToInt(paramArrayInfo.UpperLimit);
				writer.WriteElementString("LL", paramArrayInfo.LowerLimit);
				if (paramArrayInfo.Value.HasValue)
				{
					writer.WriteElementString("V", paramArrayInfo.Value.ToString());
				}
				writer.WriteElementString("UL", paramArrayInfo.UpperLimit);
			}
			writer.WriteEndElement();
		}
		catch (Exception ex)
		{
			throw new Exception("WriteParamArray " + paramArrayInfo.Name + " failed; Error: " + ex.Message);
		}
	}

	private void WriteElement(XmlTextWriter writer, string xmlTag, string xmlValue)
	{
		if (xmlValue != null && xmlValue != "")
		{
			writer.WriteElementString(xmlTag, xmlValue);
		}
	}

	private string IsHexValueConvertToInt(string limit)
	{
		if (limit.ToUpper().StartsWith("0X"))
		{
			string text = limit.Remove(0, 2);
			if (text.Length > 0)
			{
				return int.Parse(text, NumberStyles.HexNumber).ToString();
			}
			return "0";
		}
		return limit;
	}

	private void WriteParamResult(XmlTextWriter writer, ParamResult paramResultInfo)
	{
		try
		{
			writer.WriteStartElement("ParamResults");
			writer.WriteAttributeString("DT", paramResultInfo.DataType);
			writer.WriteElementString("N", paramResultInfo.Name);
			if (paramResultInfo.ReportingEnabled == true)
			{
				writer.WriteElementString("ReportingEnabled", paramResultInfo.ReportingEnabled.ToString());
			}
			WriteElement(writer, "UOM", paramResultInfo.UnitOfMeasure);
			if (paramResultInfo.Result.HasValue)
			{
				WriteElement(writer, "RES", paramResultInfo.Result.ToString());
			}
			if (paramResultInfo.Array != null && paramResultInfo.Array.Count > 0)
			{
				foreach (ArrayResult item in paramResultInfo.Array)
				{
					WriteParamArray(writer, item);
				}
			}
			else if (paramResultInfo.CHAR_Value != null && paramResultInfo.CHAR_Value != "")
			{
				if (!string.IsNullOrWhiteSpace(paramResultInfo.LowerLimit))
				{
					writer.WriteElementString("LL", paramResultInfo.LowerLimit);
				}
				writer.WriteElementString("CHAR_V", RemoveInvalidXmlChars(paramResultInfo.CHAR_Value));
				if (paramResultInfo.ExtHyperLink != null && paramResultInfo.ExtHyperLink != "")
				{
					writer.WriteElementString("ExtHyperLink", paramResultInfo.ExtHyperLink);
				}
				if (!string.IsNullOrWhiteSpace(paramResultInfo.UpperLimit))
				{
					writer.WriteElementString("UL", paramResultInfo.UpperLimit);
				}
			}
			else
			{
				paramResultInfo.LowerLimit = IsHexValueConvertToInt(paramResultInfo.LowerLimit);
				paramResultInfo.UpperLimit = IsHexValueConvertToInt(paramResultInfo.UpperLimit);
				writer.WriteElementString("LL", paramResultInfo.LowerLimit);
				if (paramResultInfo.Value.HasValue)
				{
					writer.WriteElementString("V", paramResultInfo.Value.ToString());
				}
				writer.WriteElementString("UL", paramResultInfo.UpperLimit);
			}
			WriteAdditionalData(writer, paramResultInfo.additionalInfo);
			writer.WriteEndElement();
		}
		catch (Exception ex)
		{
			throw new Exception("WriteParamResult " + paramResultInfo.Name + " failed, Error: " + ex.Message);
		}
	}

	private void WriteTesterConfig(XmlTextWriter writer, Dictionary<string, string> testConfigInfo)
	{
		try
		{
			string text = "";
			if (testConfigInfo != null && testConfigInfo.Count > 0)
			{
				writer.WriteStartElement("Information");
				if (testConfigInfo.ContainsKey("NUM_OF_UNITS") && testConfigInfo["NUM_OF_UNITS"].ToString() == "1")
				{
					testConfigInfo.Remove("NUM_OF_UNITS");
				}
				foreach (KeyValuePair<string, string> item in testConfigInfo)
				{
					if (text.Length != 0)
					{
						text += "_ _";
					}
					text = text + item.Key + "__" + item.Value;
					writer.WriteStartElement("Info");
					writer.WriteElementString("Key", item.Key);
					writer.WriteElementString("Value", item.Value);
					writer.WriteEndElement();
				}
				writer.WriteEndElement();
			}
			if (text != "")
			{
				Config.RunTitle = text;
			}
			writer.WriteElementString("RunTitle", Config.RunTitle);
		}
		catch (Exception ex)
		{
			throw new Exception("WriteTesterConfig failed, " + ex.Message);
		}
	}

	private void WriteAdditionalData(XmlTextWriter writer, Dictionary<string, string> additionalInfo)
	{
		if (additionalInfo == null || additionalInfo.Count <= 0)
		{
			return;
		}
		writer.WriteStartElement("Information");
		foreach (KeyValuePair<string, string> item in additionalInfo)
		{
			writer.WriteStartElement("Info");
			writer.WriteElementString("Key", item.Key);
			writer.WriteElementString("Value", item.Value);
			writer.WriteEndElement();
		}
		writer.WriteEndElement();
	}

	private void WriteConfig(XmlTextWriter writer, configInfo configInfo)
	{
		try
		{
			writer.WriteStartElement("Config");
			writer.WriteElementString("UUT_SN", configInfo.UUT_SN);
			WriteElement(writer, "MCN", Config.MCN);
			WriteElement(writer, "WORKSTATION", Config.WORKSTATION);
			WriteElement(writer, "TESTERID", Config.TESTERID);
			WriteElement(writer, "HW_VER", Config.HW_VER);
			WriteElement(writer, "SW_VER", Config.SW_VER);
			WriteElement(writer, "SW_MCN", Config.SW_MCN);
			WriteElement(writer, "SiteKey", Config.SiteKey);
			WriteElement(writer, "Database", Config.Database);
			WriteElement(writer, "TreeFileName", Config.TreeFileName);
			WriteElement(writer, "Server", Config.Server);
			WriteElement(writer, "RegisteredMachine", Config.RegisteredMachine);
			WriteElement(writer, "TreeType", Config.TreeType);
			WriteElement(writer, "SiteTreeID", Config.SiteTreeID);
			WriteElement(writer, "Comments", Config.Comments);
			WriteElement(writer, "HTMLLink", configInfo.HtmlLink);
			WriteElement(writer, "RequestId", configInfo.RequestID);
			SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>(additionalConfigTags);
			foreach (KeyValuePair<string, string> item in sortedDictionary)
			{
				WriteElement(writer, item.Key, item.Value);
			}
			if (Config.ExtendedData != ExtendedDataType.No)
			{
				WriteElement(writer, "ExtendedData", Config.ExtendedData.ToString());
			}
			WriteElement(writer, "SessionDataGUID", configInfo.SessionDataGuid);
			WriteElement(writer, "ErrorCodeRID", Config.ErrorCode);
			WriteElement(writer, "ERROR_CODE", Config.ErrorCode);
			WriteElement(writer, "IsRunning", configInfo.IsRunning.ToString());
			WriteTesterConfig(writer, configInfo.RunTitleTesterConfig);
			writer.WriteElementString("StartTime", configInfo.StartTime);
			writer.WriteElementString("Duration", configInfo.Duration);
			writer.WriteElementString("TreeID", configInfo.TreeID);
			writer.WriteElementString("MachineName", configInfo.MachineName);
			writer.WriteElementString("StopTime", configInfo.StopTime);
			writer.WriteElementString("Result", configInfo.Result);
			writer.WriteElementString("SessionName", configInfo.SessionName);
			writer.WriteElementString("TPByVerRID", configInfo.TPByVersionRID);
			WriteLinkedTreeInfo(writer, configInfo.LinkedFileNames);
			writer.WriteEndElement();
		}
		catch (Exception ex)
		{
			throw new Exception("WriteConfig failed, " + ex.Message);
		}
	}

	private string GetXmlFileName(string filePath, string fileName)
	{
		if (fileName == null || fileName == "")
		{
			string startTime = Config.StartTime;
			startTime = startTime.Replace(":", "_");
			startTime = startTime.Replace("/", "-");
			fileName = "\\" + Config.UUT_SN + "_" + startTime + ".xml";
		}
		if (!fileName.EndsWith(".xml"))
		{
			fileName += ".xml";
		}
		if (filePath == null || filePath == "")
		{
			filePath = "C:\\Qualcomm\\QSPR\\TestLog\\" + Environment.MachineName;
		}
		try
		{
			lock (this)
			{
				if (!Directory.Exists(filePath))
				{
					Directory.CreateDirectory(filePath);
				}
			}
			return filePath + "\\" + fileName;
		}
		catch (Exception ex)
		{
			throw new Exception("FilePath " + filePath + " is not accessible, Error:" + ex.Message);
		}
	}

	private void WriteXmlData(string filePath, string fileName, bool processDataIdentifier, bool logTestSteps = true, bool logTestCases = true, int startTestIndex = 0, int stopTestIndex = 0)
	{
		try
		{
			XmlTextWriter xmlTextWriter = new XmlTextWriter(GetXmlFileName(filePath, fileName), null);
			xmlTextWriter.WriteStartDocument();
			string text = StyleSheetPath + "\\" + StyleSheetName;
			string text2 = "type='text/xsl' href='" + text + "'";
			xmlTextWriter.WriteProcessingInstruction("xml-stylesheet", text2);
			xmlTextWriter.WriteStartElement("ROOT");
			if (string.IsNullOrWhiteSpace(Config.SessionName))
			{
				Config.SessionName = filePath + "\\" + fileName;
			}
			WriteConfig(xmlTextWriter, Config);
			if (processDataIdentifier)
			{
				ProcessDataIdentifierForTestCollection(Tests);
			}
			if (stopTestIndex == 0 && Tests != null)
			{
				stopTestIndex = Tests.Count;
			}
			if (Tests != null)
			{
				for (int i = startTestIndex; i < stopTestIndex; i++)
				{
					Test testInfo = (Test)Tests[i];
					if (ShouldWriteTest(testInfo, logTestSteps, logTestCases))
					{
						WriteTest(xmlTextWriter, testInfo);
					}
				}
			}
			xmlTextWriter.WriteEndElement();
			xmlTextWriter.WriteEndDocument();
			xmlTextWriter.Flush();
			xmlTextWriter.Close();
		}
		catch (Exception ex)
		{
			throw new Exception("WriteXml() for " + filePath + fileName + " Error: " + ex.Message);
		}
	}

	private string RemoveInvalidXmlChars(string stringToCheck)
	{
		try
		{
			if (XmlConvert.VerifyXmlChars(stringToCheck) == stringToCheck)
			{
				return stringToCheck;
			}
		}
		catch
		{
		}
		char[] value = stringToCheck.Where((char character) => XmlConvert.IsXmlChar(character)).ToArray();
		return new string(value);
	}

	private bool ShouldWriteTest(Test testInfo, bool logTestSteps, bool logTestCases)
	{
		if ("StartLogging" == testInfo.TestName || "EndLogging" == testInfo.TestName)
		{
			return false;
		}
		if (!logTestSteps && testInfo.TestCaseRefRID > 0)
		{
			return false;
		}
		if (!logTestCases && testInfo.TestCaseRID > 0)
		{
			return false;
		}
		if (logTestCases && !logTestSteps && testInfo.TestCaseRID == -1 && testInfo.TestCaseRefRID != -1)
		{
			return false;
		}
		return true;
	}

	private void WriteTest(XmlTextWriter writer, Test testInfo)
	{
		try
		{
			writer.WriteStartElement("TEST");
			writer.WriteElementString("TNAME", testInfo.TestName);
			writer.WriteElementString("RES", testInfo.TestResult);
			WriteElement(writer, "NI", testInfo.NodeIndex);
			WriteTestCaseDataElements(writer, testInfo);
			if (testInfo.TestPathInTree != null)
			{
				WriteElement(writer, "TestPath", testInfo.TestPathInTree);
			}
			if (testInfo.RealName != null)
			{
				WriteElement(writer, "RealName", testInfo.RealName);
			}
			if (testInfo.LimitsEnforced == true)
			{
				WriteElement(writer, "LimitsEnforced", testInfo.LimitsEnforced.ToString());
			}
			if (testInfo.CurrentLoopIteration.HasValue)
			{
				WriteElement(writer, "LOOP_ITERATION", testInfo.CurrentLoopIteration.ToString());
			}
			if (testInfo.MaxLoopIteration.HasValue)
			{
				WriteElement(writer, "MAX_ITERATION", testInfo.MaxLoopIteration.ToString());
			}
			if (testInfo.IsLinkedTree)
			{
				WriteLinkedTreeInfo(writer, testInfo.LinkedFiles);
			}
			WriteLoop(writer, testInfo.LoopConditions);
			if (testInfo.ParamResults != null && testInfo.ParamResults.Count > 0)
			{
				foreach (ParamResult paramResult in testInfo.ParamResults)
				{
					WriteParamResult(writer, paramResult);
				}
			}
			WriteKpiParamtersFromChildren(writer, testInfo);
			writer.WriteEndElement();
		}
		catch (Exception ex)
		{
			throw new Exception(" Error handling Test " + testInfo.TestName + "Error: " + ex.Message);
		}
	}

	private void WriteKpiParamtersFromChildren(XmlTextWriter writer, Test testInfo)
	{
		if (testInfo.ChildTests == null)
		{
			return;
		}
		foreach (Test childTest in testInfo.ChildTests)
		{
			if (childTest.ParamResults != null)
			{
				foreach (ParamResult paramResult in childTest.ParamResults)
				{
					if (paramResult.ReportingEnabled == true)
					{
						WriteParamResult(writer, paramResult);
					}
				}
			}
			WriteKpiParamtersFromChildren(writer, childTest);
		}
	}

	private void WriteTestCaseDataElements(XmlTextWriter writer, Test testInfo)
	{
		if (testInfo.ErrorCode != null)
		{
			WriteElement(writer, "ErrorCodeRID", testInfo.ErrorCode);
		}
		if (testInfo.ErrorCode != null)
		{
			WriteElement(writer, "ERROR_CODE", testInfo.ErrorCode);
		}
		_ = testInfo.TestCaseRID;
		WriteElement(writer, "TestCaseRID", testInfo.TestCaseRID.ToString());
		if (testInfo.TestCaseName != null)
		{
			WriteElement(writer, "TCName", testInfo.TestCaseName);
		}
		if (testInfo.TestStartTime != null)
		{
			WriteElement(writer, "TestStartTime", testInfo.TestStartTime);
		}
		if (testInfo.TestStopTime != null)
		{
			WriteElement(writer, "TestStopTime", testInfo.TestStopTime);
		}
		_ = testInfo.TestDuration;
		WriteElement(writer, "TestDuration", testInfo.TestDuration.ToString("c"));
		if (testInfo.BlockedCRNumber != null)
		{
			WriteElement(writer, "BlockedCRNumber", testInfo.BlockedCRNumber);
		}
		if (testInfo.Comments != null)
		{
			WriteElement(writer, "Comments", testInfo.Comments);
		}
		if (testInfo.LogFilePath != null)
		{
			WriteElement(writer, "LogFilePath", testInfo.LogFilePath);
		}
		if (testInfo.TestStepLogPath != null)
		{
			WriteElement(writer, "DetailedLogPath", testInfo.TestStepLogPath);
		}
		if (testInfo.TestCaseRefRID > -1)
		{
			WriteElement(writer, "TestCaseRefRID", testInfo.TestCaseRefRID.ToString());
		}
		if (testInfo.JIRAID != null)
		{
			WriteElement(writer, "JIRAID", testInfo.JIRAID);
		}
		if (testInfo.CRID != null)
		{
			WriteElement(writer, "CRID", testInfo.CRID);
		}
		if (testInfo.Warning != null)
		{
			WriteElement(writer, "Warning", testInfo.Warning);
		}
		if (testInfo.ErrorDesc != null)
		{
			WriteElement(writer, "ErrorDescription", testInfo.ErrorDesc);
		}
		if (testInfo.IRID != null)
		{
			WriteElement(writer, "IRID", testInfo.IRID);
		}
		if (testInfo.SRID != null)
		{
			WriteElement(writer, "SRID", testInfo.SRID);
		}
		if (testInfo.JIRACategories != null)
		{
			WriteElement(writer, "JIRACategories", testInfo.JIRACategories);
		}
	}

	private void ProcessDataIdentifierForTestCollection(ArrayList testCollection)
	{
		Dictionary<DataIdentifier, RetryCountProcessor> dictionary = new Dictionary<DataIdentifier, RetryCountProcessor>(new DataIdentifier.DataIdentifierComparer());
		RetryCountProcessor value;
		foreach (Test item in testCollection)
		{
			DataIdentifier key = new DataIdentifier(item.TestName, GetLoopDetails(item));
			if (dictionary.TryGetValue(key, out value))
			{
				value.RetryCount++;
				continue;
			}
			value = new RetryCountProcessor();
			dictionary.Add(key, value);
		}
		foreach (Test item2 in testCollection)
		{
			DataIdentifier key = new DataIdentifier(item2.TestName, GetLoopDetails(item2));
			if (dictionary.TryGetValue(key, out value))
			{
				value.ProcessedRetryCount++;
				int num = 0;
				if (value.ProcessedRetryCount == value.RetryCount)
				{
					num = 1;
				}
				item2.AddLoopCondition("RetryCount", value.ProcessedRetryCount.ToString());
				item2.AddLoopCondition("LastVisit", num.ToString());
			}
		}
	}

	public void WriteXml(string filePath, string fileName)
	{
		WriteXmlData(filePath, fileName, processDataIdentifier: false);
	}

	public void WriteXml(string filePath, string fileName, int startTestIndex, int testCountFromStartIndex)
	{
		WriteXmlData(filePath, fileName, processDataIdentifier: false, logTestSteps: true, logTestCases: true, startTestIndex, testCountFromStartIndex);
	}

	public void WriteXmlWithDataIdentifier(string filePath, string fileName, bool processDataIdentifier)
	{
		WriteXmlData(filePath, fileName, processDataIdentifier);
	}

	public void WriteXmlIncludingTestCasesAndSteps(string filePath, string fileName)
	{
		WriteXmlData(filePath, fileName, processDataIdentifier: false);
	}

	public void WriteXmlIncludingTestCasesNotSteps(string filePath, string fileName)
	{
		WriteXmlData(filePath, fileName, processDataIdentifier: false, logTestSteps: false);
	}

	public void WriteXmlTestSteps(string filePath, string fileName)
	{
		WriteXmlData(filePath, fileName, processDataIdentifier: false, logTestSteps: true, logTestCases: false);
	}

	public long WriteToDatabase(string connectionString)
	{
		long result = -1L;
		using SqlConnection conn = new SqlConnection(connectionString);
		DataTable dataTable = WriteSessionData(conn);
		if (dataTable != null && dataTable.Rows.Count == 1)
		{
			result = long.Parse(dataTable.Rows[0]["SessionDataRID"].ToString());
		}
		DataTable insertedTestData = WriteTestData(conn, dataTable);
		WriteParamData(conn, insertedTestData);
		return result;
	}

	private void WriteParamData(SqlConnection conn, DataTable insertedTestData)
	{
		if (insertedTestData != null && insertedTestData.Rows.Count == Tests.Count)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<ROOT>");
			int num = 0;
			foreach (Test item in Tests.Cast<Test>())
			{
				foreach (ParamResult item2 in item.ParamResults.Cast<ParamResult>())
				{
					stringBuilder.Append(string.Concat("<NV><NID>", insertedTestData.Rows[num]["NodeRID"], "</NID>"));
					stringBuilder.Append(string.Concat("<NDEID>", insertedTestData.Rows[num]["nodeDetailsRID"], "</NDEID>"));
					stringBuilder.Append(string.Concat("<NDID>", insertedTestData.Rows[num]["NodeDataRID"], "</NDID>"));
					stringBuilder.Append("<start>" + Config.StartTime + "</start>");
					stringBuilder.Append("<stop>" + Config.StopTime + "</stop>");
					stringBuilder.Append("<pn>" + item2.Name + "</pn>");
					stringBuilder.Append("<ll>" + (string.IsNullOrEmpty(item2.LowerLimit) ? "" : item2.LowerLimit) + "</ll>");
					stringBuilder.Append("<ul>" + (string.IsNullOrEmpty(item2.UpperLimit) ? "" : item2.UpperLimit) + "</ul>");
					stringBuilder.Append("<u>" + item2.UnitOfMeasure + "</u>");
					if (item2.Value.HasValue)
					{
						stringBuilder.Append("<nres>" + item2.Value + "</nres>");
					}
					else
					{
						stringBuilder.Append("<nres></nres>");
					}
					stringBuilder.Append("<cres>" + item2.CHAR_Value + "</cres>");
					stringBuilder.Append("<res>" + ((!item2.Result.HasValue) ? "" : item2.Result.ToString()) + "</res></NV>");
				}
				num++;
			}
			stringBuilder.Append("</ROOT>");
			SqlCommand sqlCommand = new SqlCommand("[dbo].[uspInsertParamDataTVP_2]", conn);
			sqlCommand.CommandTimeout = 300;
			sqlCommand.CommandType = CommandType.StoredProcedure;
			sqlCommand.Parameters.Add(new SqlParameter("@InputXml", stringBuilder.ToString()));
			conn.Open();
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			sqlCommand.ExecuteNonQuery();
			stopwatch.Stop();
			return;
		}
		throw new Exception("Error inserting test data. Number of tests inserted is not equal to the number of tests for the current unit");
	}

	private DataTable WriteTestData(SqlConnection conn, DataTable insertedSessionData)
	{
		if (insertedSessionData != null && insertedSessionData.Rows.Count == 1)
		{
			List<List<LoopCondition>> list = new List<List<LoopCondition>>();
			long num = -1L;
			long num2 = -1L;
			if (insertedSessionData.Rows.Count > 0)
			{
				num = long.Parse(insertedSessionData.Rows[0]["SessionDataRID"].ToString());
				num2 = long.Parse(insertedSessionData.Rows[0]["TreeID"].ToString());
			}
			int num3 = 0;
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<ROOT>");
			foreach (Test item2 in Tests.Cast<Test>())
			{
				stringBuilder.Append("<NV><I>" + num3 + "</I>");
				stringBuilder.Append("<tid>" + num2 + "</tid>");
				stringBuilder.Append("<sid>" + num + "</sid>");
				stringBuilder.Append("<start>" + Config.StartTime + "</start>");
				stringBuilder.Append("<stop>" + Config.StopTime + "</stop>");
				stringBuilder.Append("<nn>" + ((item2.RealName == null) ? "" : item2.RealName) + "</nn>");
				stringBuilder.Append("<tn>" + item2.TestName + "</tn>");
				stringBuilder.Append("<r>" + item2.TestResult + "</r>");
				string text = "";
				List<LoopCondition> list2 = new List<LoopCondition>();
				if (item2.LoopConditions != null && item2.LoopConditions.Count > 0)
				{
					foreach (LoopCondition loopCondition3 in item2.LoopConditions)
					{
						if (text.Length != 0)
						{
							text += "_ _";
						}
						text = text + loopCondition3.Key + "__" + loopCondition3.Value;
						LoopCondition loopCondition2 = new LoopCondition();
						loopCondition2.Key = loopCondition3.Key;
						loopCondition2.Value = loopCondition3.Value;
						loopCondition2.IsInputParam = loopCondition3.IsInputParam;
						LoopCondition item = loopCondition2;
						list2.Add(item);
					}
				}
				list.Add(list2);
				stringBuilder.Append("<l>" + (string.IsNullOrEmpty(text) ? string.Empty : text) + "</l></NV>");
				num3++;
			}
			stringBuilder.Append("</ROOT>");
			SqlCommand sqlCommand = new SqlCommand("[dbo].[uspInsertNodeDataTVP_2]", conn);
			sqlCommand.CommandTimeout = 300;
			sqlCommand.CommandType = CommandType.StoredProcedure;
			sqlCommand.Parameters.Add(new SqlParameter("@InputXml", stringBuilder.ToString()));
			DataSet dataSet = new DataSet();
			SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			sqlDataAdapter.Fill(dataSet);
			stopwatch.Stop();
			if (dataSet != null && dataSet.Tables.Count == 1 && dataSet.Tables[0].Rows.Count == Tests.Count)
			{
				WriteSplitConditions(dataSet.Tables[0], conn, list);
				return dataSet.Tables[0];
			}
			throw new Exception("Testdata not inserted into the database correctly");
		}
		throw new Exception("Session data not inserted correctly in the database for the current unit");
	}

	private void WriteSplitConditions(DataTable dataTable, SqlConnection conn, List<List<LoopCondition>> loopConditionTest)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("<ROOT>");
		for (int i = 0; i < dataTable.Rows.Count; i++)
		{
			foreach (LoopCondition item in loopConditionTest[i])
			{
				stringBuilder.Append("<NV><I>" + dataTable.Rows[i]["NodeDetailsRID"].ToString() + "</I>");
				stringBuilder.Append("<N>" + item.Key + "</N>");
				stringBuilder.Append("<V>" + item.Value + "</V></NV>");
			}
		}
		stringBuilder.Append("</ROOT>");
		SqlCommand sqlCommand = new SqlCommand("[dbo].[uspInsertLoopConditionsTVP]", conn);
		sqlCommand.CommandTimeout = 300;
		sqlCommand.CommandType = CommandType.StoredProcedure;
		sqlCommand.Parameters.Add(new SqlParameter("@InputXml", stringBuilder.ToString()));
		Stopwatch stopwatch = new Stopwatch();
		stopwatch.Start();
		DataSet dataSet = new DataSet();
		SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
		sqlDataAdapter.Fill(dataSet);
		stopwatch.Stop();
	}

	private DataTable WriteSessionData(SqlConnection conn)
	{
		DataTable dataTable = new DataTable();
		dataTable.Columns.Add("UUT_SN", typeof(string));
		dataTable.Columns.Add("StartTime", typeof(DateTime));
		dataTable.Columns.Add("StopTime", typeof(DateTime));
		dataTable.Columns.Add("SessionName", typeof(string));
		dataTable.Columns.Add("TreeName", typeof(string));
		dataTable.Columns.Add("TreeFileName", typeof(string));
		dataTable.Columns.Add("GlobalResult", typeof(string));
		dataTable.Columns.Add("Comments", typeof(string));
		dataTable.Columns.Add("PassFail", typeof(int));
		dataTable.Columns.Add("DvtFlag", typeof(string));
		dataTable.Columns.Add("ErrorCode", typeof(string));
		dataTable.Columns.Add("MCN", typeof(string));
		dataTable.Columns.Add("TesterID", typeof(string));
		dataTable.Columns.Add("WorkStation", typeof(string));
		dataTable.Columns.Add("MachineName", typeof(string));
		dataTable.Columns.Add("RunTitle", typeof(string));
		DataRow dataRow = dataTable.NewRow();
		dataTable.Rows.Add(dataRow);
		dataRow["UUT_SN"] = Config.UUT_SN;
		dataRow["StartTime"] = Config.StartTime;
		dataRow["StopTime"] = Config.StopTime;
		dataRow["SessionName"] = Config.SessionName;
		dataRow["TreeName"] = Config.TreeID;
		dataRow["TreeFileName"] = Config.TreeFileName;
		dataRow["GlobalResult"] = Config.Result;
		dataRow["Comments"] = Config.Comments;
		dataRow["DvtFlag"] = Config.TreeType;
		dataRow["ErrorCode"] = Config.ErrorCode;
		dataRow["MCN"] = Config.MCN;
		dataRow["TesterID"] = Config.TESTERID;
		dataRow["WorkStation"] = Config.WORKSTATION;
		dataRow["MachineName"] = Config.MachineName;
		if (string.IsNullOrEmpty(Config.RunTitle))
		{
			string text = string.Empty;
			foreach (KeyValuePair<string, string> item in Config.RunTitleTesterConfig)
			{
				if (text.Length != 0)
				{
					text += "_ _";
				}
				text = text + item.Key + "__" + item.Value;
			}
			Config.RunTitle = text;
		}
		dataRow["RunTitle"] = Config.RunTitle;
		SqlCommand sqlCommand = new SqlCommand("[dbo].[uspInsertSessionDataTVP]", conn);
		sqlCommand.CommandTimeout = 300;
		sqlCommand.CommandType = CommandType.StoredProcedure;
		SqlParameter sqlParameter = sqlCommand.Parameters.AddWithValue("@InTbl", dataTable);
		sqlParameter.SqlDbType = SqlDbType.Structured;
		DataSet dataSet = new DataSet();
		SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
		sqlDataAdapter.Fill(dataSet);
		if (dataSet != null && dataSet.Tables.Count == 1)
		{
			return dataSet.Tables[0];
		}
		throw new Exception("Session data not inserted into the database correctly");
	}

	public void WriteXml()
	{
		WriteXmlData(null, null, processDataIdentifier: false);
	}

	public void WriteXml(string filePath)
	{
		WriteXmlData(filePath, null, processDataIdentifier: false);
	}

	private string GetLoopDetails(Test testInfo)
	{
		try
		{
			string text = "";
			if (testInfo.LoopConditions != null && testInfo.LoopConditions.Count > 0)
			{
				foreach (LoopCondition loopCondition in testInfo.LoopConditions)
				{
					if (text.Length != 0)
					{
						text += "_ _";
					}
					text = text + loopCondition.Key + "__" + loopCondition.Value;
				}
			}
			return text;
		}
		catch (Exception ex)
		{
			throw new Exception("GetLoopDetails failed, " + ex.Message);
		}
	}

	private void WriteCSVData(StreamWriter csvFile, string op, string line)
	{
		try
		{
			int num = 1;
			foreach (Test test in Tests)
			{
				if (test.ParamResults == null || test.ParamResults.Count <= 0)
				{
					continue;
				}
				foreach (ParamResult paramResult in test.ParamResults)
				{
					TimeSpan testDuration = test.TestDuration;
					if (paramResult.Array != null && paramResult.Array.Count > 0)
					{
						foreach (ArrayResult item in paramResult.Array)
						{
							csvFile.WriteLine(num + "," + op + "," + Config.TESTERID + "," + line + "," + Config.MCN + "," + Config.UUT_SN + "," + item.Name + " " + GetLoopDetails(test) + "," + item.UpperLimit + "," + item.LowerLimit + "," + item.Value + "," + test.ErrorCode + "," + $"{testDuration.Seconds:f}" + "," + test.TestResult + "," + DateTime.Now);
							num++;
						}
					}
					else
					{
						csvFile.WriteLine(num + "," + op + "," + Config.TESTERID + "," + line + "," + Config.MCN + "," + Config.UUT_SN + "," + paramResult.Name + " " + GetLoopDetails(test) + "," + paramResult.UpperLimit + "," + paramResult.LowerLimit + "," + paramResult.Value + "," + test.ErrorCode + "," + $"{testDuration.Seconds:f}" + "," + test.TestResult + "," + DateTime.Now);
						num++;
					}
				}
			}
		}
		catch (Exception ex)
		{
			throw new Exception("WriteCSVData failed, " + ex.Message);
		}
	}

	private void WriteCSVHeaders(StreamWriter csvFile)
	{
		if (CSVColumnNames == null)
		{
			CSVColumnNames = new CSVColumnNames();
		}
		csvFile.WriteLine(CSVColumnNames.IDHeader + "," + CSVColumnNames.ProcessHeader + "," + CSVColumnNames.StationHeader + "," + CSVColumnNames.LineHeader + "," + CSVColumnNames.ModelHeader + "," + CSVColumnNames.SerialNoHeader + "," + CSVColumnNames.TestNameHeader + "," + CSVColumnNames.HighSpecHeader + "," + CSVColumnNames.LowSpecHeader + "," + CSVColumnNames.ResultHeader + "," + CSVColumnNames.ErrorCodeHeader + "," + CSVColumnNames.TestTimeHeader + "," + CSVColumnNames.TestStatusHeader + "," + CSVColumnNames.TestDateHeader);
	}

	private string GetCSVFileName(string filePath, string fileName)
	{
		if (fileName == null || fileName == "")
		{
			fileName = "\\" + Config.UUT_SN + Config.StartTime.ToString() + ".csv";
		}
		if (!fileName.EndsWith(".csv"))
		{
			fileName += ".csv";
		}
		if (filePath == null || filePath == "")
		{
			filePath = "C:\\Qualcomm\\QSPR\\TestLog\\" + Environment.MachineName;
		}
		try
		{
			lock (this)
			{
				if (!Directory.Exists(filePath))
				{
					Directory.CreateDirectory(filePath);
				}
			}
			return filePath + "\\" + fileName;
		}
		catch (Exception ex)
		{
			throw new Exception("FilePath " + filePath + " is not accessible, Error:" + ex.Message);
		}
	}

	public void WriteCSV(string fileName, string filePath, string op, string line)
	{
		try
		{
			string cSVFileName = GetCSVFileName(filePath, fileName);
			StreamWriter streamWriter = new StreamWriter(cSVFileName);
			WriteCSVHeaders(streamWriter);
			WriteCSVData(streamWriter, op, line);
			streamWriter.Flush();
			streamWriter.Close();
		}
		catch (Exception ex)
		{
			throw new Exception("WriteCSV failed for " + fileName + "\\" + filePath + "; Error: " + ex.Message);
		}
	}

	public DataTable ToTable()
	{
		DataTable dataTable = CreateDataTableWithSchema();
		if (Tests != null)
		{
			int num = 0;
			foreach (Test test in Tests)
			{
				num++;
				if (test.ParamResults != null)
				{
					if (test.ParamResults.Count <= 0)
					{
						continue;
					}
					foreach (ParamResult paramResult in test.ParamResults)
					{
						if (paramResult.Array != null)
						{
							if (paramResult.Array.Count <= 0)
							{
								continue;
							}
							foreach (ArrayResult item in paramResult.Array)
							{
								DataRow dataRow = dataTable.NewRow();
								AddSessionInformationToTable(dataRow, Config);
								AddTestInformationToTable(dataRow, test);
								AddParametricInformationToTable(dataRow, paramResult);
								AddParamArrayInformationToTable(dataRow, item);
								dataRow["NodeDataRID"] = num;
								dataTable.Rows.Add(dataRow);
							}
						}
						else
						{
							DataRow dataRow2 = dataTable.NewRow();
							AddSessionInformationToTable(dataRow2, Config);
							AddTestInformationToTable(dataRow2, test);
							AddParametricInformationToTable(dataRow2, paramResult);
							dataRow2["NodeDataRID"] = num;
							dataTable.Rows.Add(dataRow2);
						}
					}
				}
				else
				{
					DataRow dataRow3 = dataTable.NewRow();
					AddSessionInformationToTable(dataRow3, Config);
					AddTestInformationToTable(dataRow3, test);
					ParamResult paramInfo = new ParamResult();
					AddParametricInformationToTable(dataRow3, paramInfo);
					dataRow3["NodeDataRID"] = num;
					dataTable.Rows.Add(dataRow3);
				}
			}
		}
		return dataTable;
	}

	private void AddParamArrayInformationToTable(DataRow newRow, ArrayResult arrayParam)
	{
		if (int.TryParse(arrayParam.RowIndex, out var result))
		{
			newRow["ArrayParamIndex"] = result;
		}
		if (int.TryParse(arrayParam.ColumnIndex, out var result2))
		{
			newRow["ArrayParamColumnIndex"] = result2;
		}
		if (!string.IsNullOrEmpty(arrayParam.CHAR_Value))
		{
			newRow["ArrayParamCharResult"] = arrayParam.CHAR_Value;
		}
		if (double.TryParse(arrayParam.UpperLimit, out var result3))
		{
			newRow["ArrayUpperLimit"] = result3;
		}
		if (double.TryParse(arrayParam.LowerLimit, out var result4))
		{
			newRow["ArrayLowerLimit"] = result4;
		}
		if (arrayParam.Value.HasValue)
		{
			newRow["ArrayResult"] = arrayParam.Value;
		}
	}

	private void AddParametricInformationToTable(DataRow newRow, ParamResult paramInfo)
	{
		if (!string.IsNullOrEmpty(paramInfo.Name))
		{
			newRow["ParameterName"] = paramInfo.Name;
		}
		double result = double.NaN;
		if (double.TryParse(paramInfo.UpperLimit, out result))
		{
			newRow["UpperLimit"] = result;
		}
		double result2 = double.NaN;
		if (double.TryParse(paramInfo.LowerLimit, out result2))
		{
			newRow["LowerLimit"] = result2;
		}
		if (!string.IsNullOrEmpty(paramInfo.ExtHyperLink))
		{
			newRow["Link"] = paramInfo.ExtHyperLink;
		}
		if (paramInfo.Value.HasValue)
		{
			newRow["NumValue"] = paramInfo.Value.Value;
		}
		else
		{
			newRow["CharValue"] = paramInfo.CHAR_Value;
		}
		newRow["UOM"] = paramInfo.UnitOfMeasure;
	}

	private void AddTestInformationToTable(DataRow newRow, Test qtmXmlTest)
	{
		newRow["TestName"] = qtmXmlTest.TestName;
		newRow["RealName"] = qtmXmlTest.RealName;
		newRow["TestPath"] = qtmXmlTest.TestPathInTree;
		newRow["TestResult"] = qtmXmlTest.TestResult;
		newRow["ScnValue"] = GetLoopDetails(qtmXmlTest);
		newRow["ErrorCode"] = qtmXmlTest.ErrorCode;
		newRow["TestStartTime"] = GetDateTimeFromString(qtmXmlTest.TestStartTime);
		newRow["TestStopTime"] = GetDateTimeFromString(qtmXmlTest.TestStopTime);
		newRow["TestDuration"] = qtmXmlTest.TestDuration;
		newRow["MachineName"] = Config.MachineName;
	}

	private object GetDateTimeFromString(string dateTimeStr)
	{
		bool flag = false;
		if (!DateTime.TryParse(dateTimeStr, out var result) && !DateTime.TryParseExact(dateTimeStr, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result))
		{
			flag = true;
		}
		if (flag)
		{
			return Convert.DBNull;
		}
		return result;
	}

	private void AddSessionInformationToTable(DataRow newRow, configInfo Config)
	{
		newRow["SessionDataRID"] = -1;
		newRow["VisitNum"] = -1;
		if (Config.UUT_SN != null)
		{
			newRow["UUT_SN"] = Config.UUT_SN;
		}
		newRow["MCN"] = Config.MCN;
		newRow["TesterID"] = Config.TESTERID;
		newRow["TreeID"] = Config.TreeID;
		if (DateTime.TryParse(Config.StartTime, out var result))
		{
			newRow["StartTime"] = result;
		}
		else if (DateTime.TryParseExact(Config.StartTime, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result))
		{
			newRow["StartTime"] = result;
		}
		if (DateTime.TryParse(Config.StopTime, out result))
		{
			newRow["StopTime"] = result;
		}
		else if (DateTime.TryParseExact(Config.StopTime, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result))
		{
			newRow["StopTime"] = result;
		}
		if (long.TryParse(Config.TreeID, out var result2))
		{
			newRow["TreeID"] = result2;
		}
		newRow["GlobalResult"] = Config.Result;
		newRow["DvtFlag"] = Config.TreeType;
		newRow["WorkStation"] = Config.WORKSTATION;
		newRow["RunTitle"] = Config.RunTitle;
		newRow["TreeFileName"] = Config.TreeFileName;
		if (Config.Comments != null)
		{
			newRow["Comments"] = Config.Comments;
		}
	}

	private DataTable CreateDataTableWithSchema()
	{
		DataTable dataTable = new DataTable();
		dataTable.Columns.Add("SessionDataRID", typeof(long));
		dataTable.Columns.Add("UUT_SN", typeof(string));
		dataTable.Columns.Add("MCN", typeof(string));
		dataTable.Columns.Add("TreeID", typeof(string));
		dataTable.Columns.Add("TreeFileName", typeof(string));
		dataTable.Columns.Add("TesterID", typeof(string));
		dataTable.Columns.Add("NodeDataRID", typeof(long));
		dataTable.Columns.Add("TestName", typeof(string));
		dataTable.Columns.Add("RealName", typeof(string));
		dataTable.Columns.Add("TestPath", typeof(string));
		dataTable.Columns.Add("TestStartTime", typeof(DateTime));
		dataTable.Columns.Add("TestStopTime", typeof(DateTime));
		dataTable.Columns.Add("TestDuration");
		dataTable.Columns.Add("ParameterName", typeof(string));
		dataTable.Columns.Add("LowerLimit", typeof(double));
		dataTable.Columns.Add("NumValue", typeof(double));
		dataTable.Columns.Add("UpperLimit", typeof(double));
		dataTable.Columns.Add("CharValue", typeof(string));
		dataTable.Columns.Add("Link", typeof(string));
		dataTable.Columns.Add("UOM", typeof(string));
		dataTable.Columns.Add("TestResult", typeof(string));
		dataTable.Columns.Add("StartTime", typeof(DateTime));
		dataTable.Columns.Add("StopTime", typeof(DateTime));
		dataTable.Columns.Add("VisitNum", typeof(int));
		dataTable.Columns.Add("GlobalResult", typeof(string));
		dataTable.Columns.Add("DvtFlag", typeof(string));
		dataTable.Columns.Add("ScnValue", typeof(string));
		dataTable.Columns.Add("ArrayParamIndex", typeof(int));
		dataTable.Columns.Add("ArrayParamColumnIndex", typeof(int));
		dataTable.Columns.Add("ArrayLowerLimit", typeof(double));
		dataTable.Columns.Add("ArrayResult", typeof(double));
		dataTable.Columns.Add("ArrayUpperLimit", typeof(double));
		dataTable.Columns.Add("ArrayParamCharResult", typeof(string));
		dataTable.Columns.Add("RunTitle", typeof(string));
		dataTable.Columns.Add("PassFail", typeof(int));
		dataTable.Columns.Add("LastVisit", typeof(int));
		dataTable.Columns.Add("WorkStation", typeof(string));
		dataTable.Columns.Add("ErrorCode", typeof(string));
		dataTable.Columns.Add("Comments", typeof(string));
		dataTable.Columns.Add("MachineName", typeof(string));
		return dataTable;
	}

	private DateTime GetDateTimeFromFormatString(string timestampStr)
	{
		DateTime result = DateTime.MinValue;
		if (DateTime.TryParse(timestampStr, out result))
		{
			return result;
		}
		if (DateTime.TryParseExact(timestampStr, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result))
		{
			return result;
		}
		return DateTime.Parse(timestampStr);
	}

	public void ConvertTestData(ITestDataConvertor dataConvertor, Dictionary<string, string> globalVariables)
	{
		new CultureInfo("en-US");
		dataConvertor.InitializeGlobalVariables(globalVariables);
		dataConvertor.StartConversion();
		dataConvertor.WriteConfiguration(Config.UUT_SN, Config.Result, GetDateTimeFromFormatString(Config.StartTime), GetDateTimeFromFormatString(Config.StopTime), Config.TESTERID, Config.TreeID, Config.WORKSTATION, Config.MCN, Config.Comments, Config.ErrorCode, Config.TreeFileName, Config.TreeType);
		if (Tests != null)
		{
			foreach (Test test in Tests)
			{
				dataConvertor.WriteTest(test.TestName, test.TestResult, test.ErrorCode, test.TestDuration);
				if (test.LoopConditions != null && test.LoopConditions.Count > 0)
				{
					foreach (LoopCondition loopCondition in test.LoopConditions)
					{
						dataConvertor.WriteLoopInfo(loopCondition.Key, loopCondition.Value);
					}
				}
				if (test.ParamResults == null || test.ParamResults.Count <= 0)
				{
					continue;
				}
				foreach (ParamResult paramResult in test.ParamResults)
				{
					WriteParametricResult(dataConvertor, paramResult);
				}
			}
		}
		dataConvertor.StopConversion();
	}

	private void WriteParametricResult(ITestDataConvertor dataConvertor, ParamResult parameter)
	{
		if (parameter.Array == null || parameter.Array.Count < 1)
		{
			double result = double.NaN;
			double result2 = double.NaN;
			double.TryParse(parameter.LowerLimit, out result);
			double.TryParse(parameter.UpperLimit, out result2);
			double? lowerLimit = null;
			double? upperLimit = null;
			if (!double.IsNaN(result))
			{
				lowerLimit = result;
			}
			if (!double.IsNaN(result2))
			{
				upperLimit = result2;
			}
			dataConvertor.WriteParameter(parameter.Name, parameter.UnitOfMeasure, parameter.CHAR_Value, lowerLimit, upperLimit, parameter.Value);
			return;
		}
		List<string> list = new List<string>();
		List<double?> list2 = new List<double?>();
		List<double?> list3 = new List<double?>();
		List<double?> list4 = new List<double?>();
		foreach (ArrayResult item3 in parameter.Array)
		{
			double result3 = double.NaN;
			double result4 = double.NaN;
			double.TryParse(item3.LowerLimit, out result3);
			double.TryParse(item3.UpperLimit, out result4);
			double? item = null;
			double? item2 = null;
			if (!double.IsNaN(result3))
			{
				item = result3;
			}
			if (!double.IsNaN(result4))
			{
				item2 = result4;
			}
			list.Add(item3.CHAR_Value);
			list4.Add(item3.Value);
			list2.Add(item);
			list3.Add(item2);
		}
		dataConvertor.WriteArrayParameter(parameter.Name, parameter.UnitOfMeasure, list.ToArray(), list2.ToArray(), list3.ToArray(), list4.ToArray());
	}

	public static DateTime RoundDateTimeToNearestMilliSecond(DateTime time)
	{
		return time.AddTicks(-(time.Ticks % TimeSpan.FromMilliseconds(1.0).Ticks));
	}

	public void AddLoopConditionsToCurrentTest(Dictionary<string, string> loops)
	{
		try
		{
			if (currTest != null)
			{
				foreach (string key in loops.Keys)
				{
					currTest.AddLoopCondition(key, loops[key]);
				}
				return;
			}
			throw new Exception("Current Test is null");
		}
		catch (Exception ex)
		{
			throw new Exception("AddLoopConditionsToCurrentTest failed, Error: " + ex.Message);
		}
	}
}
