using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace QC.QTMXmlSchema;

[Serializable]
[XmlRoot(Namespace = "", IsNullable = false)]
[XmlType(AnonymousType = true)]
public class ROOT
{
	private CultureInfo _stringFormatProvider = CultureInfo.InvariantCulture;

	private Config configField;

	private ROOTTEST[] tESTField;

	[XmlElement("Config")]
	public Config ConfigInfo
	{
		get
		{
			return configField;
		}
		set
		{
			configField = value;
		}
	}

	[XmlElement("TEST")]
	public ROOTTEST[] TEST
	{
		get
		{
			return tESTField;
		}
		set
		{
			tESTField = value;
		}
	}

	public static ROOT LoadFromFile(string xmlFilePath)
	{
		ROOT result = null;
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(ROOT));
		FileStream fileStream = null;
		if (File.Exists(xmlFilePath))
		{
			try
			{
				fileStream = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read);
				XmlTextReader xmlReader = new XmlTextReader(fileStream);
				result = (ROOT)xmlSerializer.Deserialize(xmlReader);
			}
			finally
			{
				fileStream.Close();
			}
		}
		return result;
	}

	public QTMFormatUnitData ConvertToQtmFormatUnitData()
	{
		QTMFormatUnitData qTMFormatUnitData = new QTMFormatUnitData();
		if (ConfigInfo != null)
		{
			QTMFormatUnitData.ExtendedDataType extendedData = QTMFormatUnitData.ExtendedDataType.No;
			QTMFormatUnitData.Result treeResult = QTMFormatUnitData.Result.Exception;
			if (!string.IsNullOrEmpty(ConfigInfo.ExtendedData) && ConfigInfo.ExtendedData.ToLower() == "yes")
			{
				extendedData = QTMFormatUnitData.ExtendedDataType.Yes;
			}
			if (!string.IsNullOrEmpty(ConfigInfo.Result))
			{
				if (ConfigInfo.Result.ToLower() == "passed")
				{
					treeResult = QTMFormatUnitData.Result.Passed;
				}
				else if (ConfigInfo.Result.ToLower() == "failed")
				{
					treeResult = QTMFormatUnitData.Result.Failed;
				}
			}
			string computerName = string.Empty;
			if (ConfigInfo.MachineName != null)
			{
				if (ConfigInfo.MachineName is XmlNode[])
				{
					XmlNode[] array = (XmlNode[])ConfigInfo.MachineName;
					if (array != null && array.Length > 0)
					{
						computerName = array[0].Value;
					}
				}
				else if (ConfigInfo.MachineName is string)
				{
					string text = ConfigInfo.MachineName.ToString();
					if (!string.IsNullOrEmpty(text))
					{
						computerName = text;
					}
				}
			}
			qTMFormatUnitData.AddStandardConfig(ConfigInfo.UUT_SN, treeResult, ConfigInfo.StartTime, ConfigInfo.StopTime, ConfigInfo.TESTERID, ConfigInfo.TreeID, ConfigInfo.WORKSTATION, ConfigInfo.MCN, ConfigInfo.Comments, extendedData, ConfigInfo.ERROR_CODE, ConfigInfo.TreeFileName, ConfigInfo.TreeType, computerName, ConfigInfo.WORKSTATION, ConfigInfo.SW_MCN, "", ConfigInfo.SW_VER, "", ConfigInfo.Database, ConfigInfo.Server, "");
			if (!string.IsNullOrEmpty(ConfigInfo.RunTitle))
			{
				qTMFormatUnitData.Config.RunTitle = ConfigInfo.RunTitle;
			}
			if (ConfigInfo.Information != null)
			{
				ROOTConfigInfo[] information = ConfigInfo.Information;
				foreach (ROOTConfigInfo rOOTConfigInfo in information)
				{
					qTMFormatUnitData.AddConfig(rOOTConfigInfo.Key, rOOTConfigInfo.Value);
				}
			}
		}
		if (TEST != null)
		{
			ROOTTEST[] tEST = TEST;
			foreach (ROOTTEST rOOTTEST in tEST)
			{
				QTMFormatUnitData.Result testResult = QTMFormatUnitData.Result.Exception;
				if (!string.IsNullOrEmpty(rOOTTEST.RES))
				{
					if (rOOTTEST.RES.ToLower() == "passed")
					{
						testResult = QTMFormatUnitData.Result.Passed;
					}
					else if (rOOTTEST.RES.ToLower() == "failed")
					{
						testResult = QTMFormatUnitData.Result.Failed;
					}
				}
				DateTime result = DateTime.MinValue;
				DateTime result2 = DateTime.MinValue;
				TimeSpan result3 = TimeSpan.MinValue;
				int testCaseId = -1;
				int testCaseRefId = -1;
				Test test = null;
				test = ((DateTime.TryParse(rOOTTEST.TestStartTime, out result) && DateTime.TryParse(rOOTTEST.TestStopTime, out result2) && TimeSpan.TryParse(rOOTTEST.TestDuration, out result3)) ? qTMFormatUnitData.AddTest(rOOTTEST.TNAME, testResult, rOOTTEST.NI, result, result2, result3, rOOTTEST.ERROR_CODE, testCaseId, testCaseRefId, rOOTTEST.Comments, rOOTTEST.LogFilePath, rOOTTEST.JIRAID, rOOTTEST.CRID, rOOTTEST.Warning, rOOTTEST.ErrorDescription, rOOTTEST.IRID, rOOTTEST.SRID, rOOTTEST.JIRACategories) : ((!DateTime.TryParseExact(rOOTTEST.TestStartTime, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result) || !DateTime.TryParseExact(rOOTTEST.TestStopTime, "M/d/yy HH:mm:ss:fff", _stringFormatProvider, DateTimeStyles.None, out result2) || !TimeSpan.TryParseExact(rOOTTEST.TestDuration, "c", _stringFormatProvider, out result3)) ? qTMFormatUnitData.AddTest(rOOTTEST.TNAME, testResult, rOOTTEST.NI, TimeSpan.Zero, rOOTTEST.ERROR_CODE) : qTMFormatUnitData.AddTest(rOOTTEST.TNAME, testResult, rOOTTEST.NI, result, result2, result3, rOOTTEST.ERROR_CODE, testCaseId, testCaseRefId, rOOTTEST.Comments, rOOTTEST.LogFilePath, rOOTTEST.JIRAID, rOOTTEST.CRID, rOOTTEST.Warning, rOOTTEST.ErrorDescription, rOOTTEST.IRID, rOOTTEST.SRID, rOOTTEST.JIRACategories)));
				if (test != null)
				{
					test.RealName = rOOTTEST.RealName;
					test.TestPathInTree = rOOTTEST.TestPath;
				}
				int? currentLoopIteration = null;
				int? maxLoopIteration = null;
				if (rOOTTEST.LOOP_ITERATION != null)
				{
					int result4 = 0;
					if (int.TryParse(rOOTTEST.LOOP_ITERATION, out result4))
					{
						currentLoopIteration = result4;
					}
				}
				if (rOOTTEST.MAX_ITERATION != null)
				{
					int result5 = 0;
					if (int.TryParse(rOOTTEST.MAX_ITERATION, out result5))
					{
						maxLoopIteration = result5;
					}
				}
				test.CurrentLoopIteration = currentLoopIteration;
				test.MaxLoopIteration = maxLoopIteration;
				if (rOOTTEST.Inputs != null)
				{
					ROOTTESTInput[] inputs = rOOTTEST.Inputs;
					foreach (ROOTTESTInput rOOTTESTInput in inputs)
					{
						bool isInputParam = rOOTTESTInput.TypeAttribute == Type.I;
						qTMFormatUnitData.AddLoopConditionsToCurrentTest(rOOTTESTInput.Key, rOOTTESTInput.Value, isInputParam);
					}
				}
				else if (rOOTTEST.LOOPVALUES != null && rOOTTEST.LOOPVALUES.LV != null && !string.IsNullOrEmpty(rOOTTEST.LOOPVALUES.LV.V))
				{
					foreach (KeyValuePair<string, string> item in GetSplitLoopConditionsFromCombinedLoopString(rOOTTEST.LOOPVALUES.LV.V))
					{
						qTMFormatUnitData.AddLoopConditionsToCurrentTest(item.Key, item.Value);
					}
				}
				if (rOOTTEST.ParamResults == null)
				{
					continue;
				}
				ROOTTESTParamResults[] paramResults = rOOTTEST.ParamResults;
				foreach (ROOTTESTParamResults rOOTTESTParamResults in paramResults)
				{
					if (!string.IsNullOrEmpty(rOOTTESTParamResults.V))
					{
						if (!double.TryParse(rOOTTESTParamResults.V, out var result6))
						{
							throw new Exception("Parameter " + rOOTTESTParamResults.N + " has an value which is not of type double ");
						}
						qTMFormatUnitData.AddParamToCurrentTest(rOOTTESTParamResults.N, rOOTTESTParamResults.UOM, result6, rOOTTESTParamResults.UL, rOOTTESTParamResults.LL, null, rOOTTESTParamResults.DataTypeAttribute);
					}
					else
					{
						qTMFormatUnitData.AddParamToCurrentTest(rOOTTESTParamResults.N, rOOTTESTParamResults.UOM, rOOTTESTParamResults.CHAR_V);
					}
					if (rOOTTESTParamResults.ParamArrayResults == null)
					{
						continue;
					}
					ROOTTESTParamArrayResults[] paramArrayResults = rOOTTESTParamResults.ParamArrayResults;
					foreach (ROOTTESTParamArrayResults rOOTTESTParamArrayResults in paramArrayResults)
					{
						if (!string.IsNullOrEmpty(rOOTTESTParamArrayResults.V))
						{
							qTMFormatUnitData.AddArrayItemToCurrParam(rOOTTESTParamArrayResults.N, rOOTTESTParamArrayResults.I, rOOTTESTParamArrayResults.CI, double.Parse(rOOTTESTParamArrayResults.V), rOOTTESTParamArrayResults.UL, rOOTTESTParamArrayResults.LL);
						}
						else
						{
							qTMFormatUnitData.AddArrayItemToCurrParam(rOOTTESTParamArrayResults.N, rOOTTESTParamArrayResults.I, rOOTTESTParamArrayResults.CI, rOOTTESTParamArrayResults.CHAR_V);
						}
					}
				}
			}
		}
		return qTMFormatUnitData;
	}

	public static Dictionary<string, string> GetSplitLoopConditionsFromCombinedLoopString(string combinedLoopString)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		string[] separator = new string[2] { "_ _", "_._" };
		string[] separator2 = new string[1] { "__" };
		string[] array = combinedLoopString.Split(separator, StringSplitOptions.RemoveEmptyEntries);
		string[] array2 = array;
		foreach (string text in array2)
		{
			string[] array3 = text.Split(separator2, StringSplitOptions.None);
			if (array3.Length == 2 && !dictionary.ContainsKey(array3[0]))
			{
				dictionary.Add(array3[0], array3[1]);
			}
		}
		return dictionary;
	}

	public static void WriteToFile(ROOT qtmXmlContents, string xmlFilePath)
	{
		XmlSerializer xmlSerializer = new XmlSerializer(qtmXmlContents.GetType());
		StreamWriter streamWriter = null;
		if (File.Exists(xmlFilePath))
		{
			try
			{
				streamWriter = new StreamWriter(xmlFilePath, append: false);
				XmlTextWriter xmlWriter = new XmlTextWriter(streamWriter);
				xmlSerializer.Serialize(xmlWriter, qtmXmlContents);
			}
			finally
			{
				streamWriter.Close();
			}
		}
	}
}
