using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Windows.Forms;
using System.Xml;
using QC.QSPRTreeSchemaLibrary;

namespace QSPR3xttParse;

[Guid("13FE32AD-4BF8-495f-AB4D-6C61BD464678")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("QSPR3XTT.reader")]
public class QSPR3XTT : _QSPR3XTT
{
	private string mXttFilePath;

	private List<TestInfo> TestInfos;

	public QSPR3XTT()
	{
		mXttFilePath = "";
		TestInfos = new List<TestInfo>();
	}

	private void PrintDotNetTestParameters(DotNetTestProperties DotNetTestProperties, ref TestInfo testInfo, string testIndex, int LCIndex, LoopScenarioValues scenarios)
	{
		if (LCIndex == -1)
		{
			for (int i = 0; i < DotNetTestProperties.Parameters.ParameterCls.Count; i++)
			{
				TestParameter param = new TestParameter();
				QC.QSPRTreeSchemaLibrary.TestParameter testParameter = (QC.QSPRTreeSchemaLibrary.TestParameter)DotNetTestProperties.Parameters.ParameterCls[i];
				param.mParameterName = testParameter.Name;
				param.mParameterValue = testParameter.Value;
				param.mUnit = testParameter.Unit;
				param.mUpperlimit = testParameter.UpperLimit;
				param.mLowerlimit = testParameter.LowerLimit;
				param.mDataType = testParameter.DataType;
				param.mParamMode = testParameter.Type;
				testInfo.AddParameter(ref param);
			}
			return;
		}
		for (int j = 0; j < DotNetTestProperties.Parameters.ParameterCls.Count; j++)
		{
			TestParameter param2 = new TestParameter();
			QC.QSPRTreeSchemaLibrary.TestParameter testParameter2 = (QC.QSPRTreeSchemaLibrary.TestParameter)DotNetTestProperties.Parameters.ParameterCls[j];
			if (scenarios != null)
			{
				for (int k = 0; k < scenarios.LoopConditions.Count; k++)
				{
					LoopCondition loopCondition = (LoopCondition)scenarios.LoopConditions[k];
					if ((DotNetTestProperties.TestName == loopCondition.TestName && testIndex == loopCondition.TestIndex) || loopCondition.TestName == "ALLTests")
					{
						if (testParameter2.Name == loopCondition.ParamName)
						{
							param2.mParameterName = testParameter2.Name;
							param2.mParameterValue = loopCondition.LoopValues[LCIndex].ToString();
							break;
						}
						param2.mParameterName = testParameter2.Name;
						param2.mParameterValue = testParameter2.Value;
					}
					else
					{
						param2.mParameterName = testParameter2.Name;
						param2.mParameterValue = testParameter2.Value;
					}
				}
			}
			else
			{
				param2.mParameterName = testParameter2.Name;
				param2.mParameterValue = testParameter2.Value;
			}
			param2.mUnit = testParameter2.Unit;
			param2.mUpperlimit = testParameter2.UpperLimit;
			param2.mLowerlimit = testParameter2.LowerLimit;
			param2.mDataType = testParameter2.DataType;
			param2.mParamMode = testParameter2.Type;
			testInfo.AddParameter(ref param2);
		}
	}

	private void PrintTestParameters_V2(HiveTestProperties HiveProperties, ref TestInfo testInfo, string testIndex, int LCIndex, LoopScenarioValues scenarios)
	{
		if (LCIndex == -1)
		{
			if (HiveProperties != null && HiveProperties.Parameters != null && HiveProperties.Parameters.ParameterCls != null)
			{
				for (int i = 0; i < HiveProperties.Parameters.ParameterCls.Count; i++)
				{
					TestParameter param = new TestParameter();
					QC.QSPRTreeSchemaLibrary.TestParameter testParameter = (QC.QSPRTreeSchemaLibrary.TestParameter)HiveProperties.Parameters.ParameterCls[i];
					param.mParameterName = testParameter.Name;
					param.mParameterValue = testParameter.Value;
					param.mUnit = testParameter.Unit;
					param.mUpperlimit = testParameter.UpperLimit;
					param.mLowerlimit = testParameter.LowerLimit;
					param.mDataType = testParameter.DataType;
					param.mParamMode = testParameter.Type;
					testInfo.AddParameter(ref param);
				}
			}
		}
		else
		{
			if (HiveProperties == null || HiveProperties.Parameters == null || HiveProperties.Parameters.ParameterCls == null)
			{
				return;
			}
			for (int j = 0; j < HiveProperties.Parameters.ParameterCls.Count; j++)
			{
				TestParameter param2 = new TestParameter();
				QC.QSPRTreeSchemaLibrary.TestParameter testParameter2 = (QC.QSPRTreeSchemaLibrary.TestParameter)HiveProperties.Parameters.ParameterCls[j];
				param2.mParameterName = "PARAM_UNKNOWN";
				param2.mParameterValue = "PARAM__VALUE_UNKNOWN";
				if (scenarios != null)
				{
					for (int k = 0; k < scenarios.LoopConditions.Count; k++)
					{
						LoopCondition loopCondition = (LoopCondition)scenarios.LoopConditions[k];
						if ((HiveProperties.TestName == loopCondition.TestName && testIndex == loopCondition.TestIndex) || loopCondition.TestName == "ALLTests")
						{
							if (testParameter2.Name == loopCondition.ParamName)
							{
								param2.mParameterName = testParameter2.Name;
								param2.mParameterValue = loopCondition.LoopValues[LCIndex].ToString();
								break;
							}
							param2.mParameterName = testParameter2.Name;
							param2.mParameterValue = testParameter2.Value;
						}
						else
						{
							param2.mParameterName = testParameter2.Name;
							param2.mParameterValue = testParameter2.Value;
						}
					}
				}
				else
				{
					param2.mParameterName = testParameter2.Name;
					param2.mParameterValue = testParameter2.Value;
				}
				param2.mUnit = testParameter2.Unit;
				param2.mUpperlimit = testParameter2.UpperLimit;
				param2.mLowerlimit = testParameter2.LowerLimit;
				param2.mDataType = testParameter2.DataType;
				param2.mParamMode = testParameter2.Type;
				testInfo.AddParameter(ref param2);
			}
		}
	}

	public bool LoadRFCalXTT(string path)
	{
		bool flag = true;
		SerializeComponents serializeComponents = QSPRTreeSchema.LoadTree(path);
		if (serializeComponents != null)
		{
			for (int i = 0; i < serializeComponents.theRootTest.TestList.Count; i++)
			{
				FolderTest folderTest = (FolderTest)serializeComponents.theRootTest.TestList[i];
				for (int j = 0; j < folderTest.TestList.Count; j++)
				{
					if (folderTest.TestList[j].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.HiveTest")
					{
						HiveTest hiveTest = (HiveTest)folderTest.TestList[j];
						PrintHiveTest(hiveTest, -1, null);
					}
					else if (folderTest.TestList[j].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.DotNetTest")
					{
						DotNetTest doNetTest = (DotNetTest)folderTest.TestList[j];
						PrintDoNetTest(doNetTest, -1, null);
					}
					else if (folderTest.TestList[j].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.FolderTest")
					{
						PrintFolder((FolderTest)folderTest.TestList[j], -1, null);
					}
				}
				flag = true;
			}
			return true;
		}
		return false;
	}

	private void PrintHiveTest(HiveTest HiveTest, int LCIndex, LoopScenarioValues scenarios)
	{
		if (HiveTest.Properties.CheckStateTest == CheckState.Checked)
		{
			if (LCIndex == -1)
			{
				TestInfo testInfo = new TestInfo(HiveTest.HiveProperties.TestName, HiveTest.HiveProperties.RealName);
				PrintTestParameters_V2(HiveTest.HiveProperties, ref testInfo, HiveTest.Index, -1, null);
				TestInfos.Add(testInfo);
			}
			else if ((bool)scenarios.ConditionCheck[LCIndex])
			{
				TestInfo testInfo2 = ((scenarios.Descriptions[LCIndex] == "") ? new TestInfo(HiveTest.HiveProperties.TestName, HiveTest.HiveProperties.RealName) : new TestInfo(string.Concat(HiveTest.HiveProperties.TestName, "(", scenarios.Descriptions[LCIndex], ")"), HiveTest.HiveProperties.RealName));
				PrintTestParameters_V2(HiveTest.HiveProperties, ref testInfo2, HiveTest.Index, LCIndex, scenarios);
				TestInfos.Add(testInfo2);
			}
		}
	}

	private string FormatDotNetRealName(string originalRealName)
	{
		string result = originalRealName;
		string[] array = originalRealName.Split('.');
		if (array.Length > 2 && array[0].Contains("QSEQ"))
		{
			result = "QSEQ" + array[2];
		}
		return result;
	}

	private void PrintDoNetTest(DotNetTest DoNetTest, int LCIndex, LoopScenarioValues scenarios)
	{
		if (DoNetTest.Properties.CheckStateTest == CheckState.Checked)
		{
			if (LCIndex == -1)
			{
				string realName = FormatDotNetRealName(DoNetTest.DotNetProperties.RealName);
				TestInfo testInfo = new TestInfo(DoNetTest.DotNetProperties.TestName, realName);
				PrintDotNetTestParameters(DoNetTest.DotNetProperties, ref testInfo, DoNetTest.Index, LCIndex, null);
				TestInfos.Add(testInfo);
			}
			else if ((bool)scenarios.ConditionCheck[LCIndex])
			{
				string realName2 = FormatDotNetRealName(DoNetTest.DotNetProperties.RealName);
				TestInfo testInfo2 = ((scenarios.Descriptions[LCIndex] == "") ? new TestInfo(DoNetTest.DotNetProperties.TestName, realName2) : new TestInfo(string.Concat(DoNetTest.DotNetProperties.TestName, "(", scenarios.Descriptions[LCIndex], ")"), realName2));
				PrintDotNetTestParameters(DoNetTest.DotNetProperties, ref testInfo2, DoNetTest.Index, LCIndex, scenarios);
				TestInfos.Add(testInfo2);
			}
		}
	}

	private void PrintFolder(FolderTest Folder, int LCIndex, LoopScenarioValues parent_scenarios)
	{
		if (Folder.Properties.Scenarios != null)
		{
			LoopScenarioValues scenarios = Folder.Properties.Scenarios;
			int count = Folder.Properties.Scenarios.ConditionCheck.Count;
			for (int i = 0; i < count; i++)
			{
				for (int j = 0; j < Folder.TestList.Count; j++)
				{
					if (Folder.TestList[j].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.HiveTest")
					{
						HiveTest hiveTest = (HiveTest)Folder.TestList[j];
						PrintHiveTest(hiveTest, i, scenarios);
					}
					else if (Folder.TestList[j].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.DotNetTest")
					{
						DotNetTest doNetTest = (DotNetTest)Folder.TestList[j];
						PrintDoNetTest(doNetTest, i, scenarios);
					}
					else if (Folder.TestList[j].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.FolderTest")
					{
						PrintFolder((FolderTest)Folder.TestList[j], i, scenarios);
					}
				}
			}
			return;
		}
		if (parent_scenarios != null)
		{
			for (int k = 0; k < Folder.TestList.Count; k++)
			{
				if (Folder.TestList[k].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.HiveTest")
				{
					HiveTest hiveTest2 = (HiveTest)Folder.TestList[k];
					PrintHiveTest(hiveTest2, LCIndex, parent_scenarios);
				}
				else if (Folder.TestList[k].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.DotNetTest")
				{
					DotNetTest doNetTest2 = (DotNetTest)Folder.TestList[k];
					PrintDoNetTest(doNetTest2, LCIndex, parent_scenarios);
				}
				else if (Folder.TestList[k].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.FolderTest")
				{
					PrintFolder((FolderTest)Folder.TestList[k], LCIndex, parent_scenarios);
				}
			}
			return;
		}
		for (int l = 0; l < Folder.TestList.Count; l++)
		{
			if (Folder.TestList[l].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.HiveTest")
			{
				HiveTest hiveTest3 = (HiveTest)Folder.TestList[l];
				PrintHiveTest(hiveTest3, -1, null);
			}
			else if (Folder.TestList[l].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.DotNetTest")
			{
				DotNetTest doNetTest3 = (DotNetTest)Folder.TestList[l];
				PrintDoNetTest(doNetTest3, -1, null);
			}
			else if (Folder.TestList[l].GetType().ToString() == "QC.QSPRTreeSchemaLibrary.FolderTest")
			{
				PrintFolder((FolderTest)Folder.TestList[l], -1, null);
			}
		}
	}

	public string GetTestName(int index)
	{
		if (index < TestInfos.Count)
		{
			return TestInfos[index].GetTestName();
		}
		return "";
	}

	public string GetRealName(int index)
	{
		if (index < TestInfos.Count)
		{
			return TestInfos[index].GetRealName();
		}
		return "";
	}

	public int GetNumOfTestParameter(int index)
	{
		if (index < TestInfos.Count)
		{
			return TestInfos[index].GetNumOfTestParameter();
		}
		return 0;
	}

	public string GetTestParameterName(int testIndex, int parameterIndex)
	{
		string result = "";
		if (testIndex < TestInfos.Count)
		{
			TestParameter param = new TestParameter();
			TestInfos[testIndex].GetParameter(parameterIndex, ref param);
			result = param.mParameterName;
		}
		return result;
	}

	public string GetTestParameterValue(int testIndex, int parameterIndex)
	{
		string result = "";
		if (testIndex < TestInfos.Count)
		{
			TestParameter param = new TestParameter();
			TestInfos[testIndex].GetParameter(parameterIndex, ref param);
			result = param.mParameterValue;
		}
		return result;
	}

	public void CreateINI(string INIpath)
	{
		StreamWriter streamWriter = new StreamWriter(INIpath);
		if (streamWriter == null)
		{
			return;
		}
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		dictionary.Add("Watch for Messages ?", "");
		dictionary.Add("Text Marker", "");
		dictionary.Add("Marker Args", "");
		dictionary.Add("Use Config Lookup For Marker Args", "");
		string value = "; ###############################################################################\n; #\n; # This file was generated by QSPR3XttParse.  The data contained within this\n; # file was transformed from a Qualcomm QSPR XTT file to INI format.\n; #\n; # File: " + INIpath + "\n; # Source File: " + mXttFilePath + "\n; # Test Count " + TestInfos.Count + "\n; ###############################################################################\n";
		streamWriter.WriteLine(value);
		streamWriter.WriteLine();
		for (int i = 0; i < TestInfos.Count; i++)
		{
			streamWriter.WriteLine("[" + TestInfos[i].GetTestName() + "]");
			streamWriter.WriteLine("realname=" + TestInfos[i].GetRealName());
			for (int j = 0; j < TestInfos[i].GetNumOfTestParameter(); j++)
			{
				TestParameter param = new TestParameter();
				TestInfos[i].GetParameter(j, ref param);
				if (!dictionary.ContainsKey(param.mParameterName))
				{
					streamWriter.WriteLine("param." + param.mParameterName + ".value=" + param.mParameterValue);
					if (param.mParamMode.Equals("Output"))
					{
						streamWriter.WriteLine("param." + param.mParameterName + ".ul=" + param.mUpperlimit);
						streamWriter.WriteLine("param." + param.mParameterName + ".ll=" + param.mLowerlimit);
					}
				}
			}
			streamWriter.WriteLine();
		}
		streamWriter.Flush();
		streamWriter.Close();
	}

	public int GetNumOfTests()
	{
		return TestInfos.Count;
	}

	public bool LoadQSPRTreeFile(string path)
	{
		return LoadRFCalXTT(path);
	}

	public void GetTestInfo(int testIndex, out string testname, out string realname, out int numParams)
	{
		testname = "";
		realname = "";
		numParams = 0;
		if (testIndex < TestInfos.Count)
		{
			testname = TestInfos[testIndex].GetTestName();
			realname = TestInfos[testIndex].GetRealName();
			numParams = TestInfos[testIndex].GetNumOfTestParameter();
		}
	}

	public void GetTestParameterInfo(int testIndex, int parameterIndex, out string parameterName, out string parameterValue, out string unit, out string upperlimit, out string lowerlimit, out string dataType, out string paramMode)
	{
		parameterName = "";
		parameterValue = "";
		unit = "";
		upperlimit = "";
		lowerlimit = "";
		dataType = "";
		paramMode = "";
		if (testIndex < TestInfos.Count)
		{
			TestParameter param = new TestParameter();
			TestInfos[testIndex].GetParameter(parameterIndex, ref param);
			parameterName = param.mParameterName;
			parameterValue = param.mParameterValue;
			unit = param.mUnit;
			upperlimit = param.mUpperlimit;
			lowerlimit = param.mLowerlimit;
			dataType = param.mDataType;
			paramMode = param.mParamMode;
		}
	}

	public void GeneratePublicPrivateRSAKeys(string seed, out string publicKey, out string privateKey)
	{
		publicKey = "";
		privateKey = "";
		try
		{
			CspParameters cspParameters = new CspParameters();
			cspParameters.KeyContainerName = seed;
			cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
			RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(cspParameters);
			publicKey = rSACryptoServiceProvider.ToXmlString(includePrivateParameters: false);
			privateKey = rSACryptoServiceProvider.ToXmlString(includePrivateParameters: true);
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
	}

	public void DigSignQSPRTreeFile(string inFile, string outFile, string privateKey)
	{
		try
		{
			RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
			rSACryptoServiceProvider.FromXmlString(privateKey);
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.PreserveWhitespace = true;
			xmlDocument.Load(inFile);
			SignXml(xmlDocument, rSACryptoServiceProvider);
			xmlDocument.Save(outFile);
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
	}

	public bool LoadSignedQSPRTreeFile(string path, string publicKey)
	{
		bool flag = false;
		try
		{
			RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
			rSACryptoServiceProvider.FromXmlString(publicKey);
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.PreserveWhitespace = true;
			xmlDocument.Load(path);
			Console.WriteLine("Verifying signature...");
			flag = VerifyXml(xmlDocument, rSACryptoServiceProvider);
			if (flag)
			{
				Console.WriteLine("The XML signature is valid.");
				flag = LoadQSPRTreeFile(path);
			}
			else
			{
				Console.WriteLine("The XML signature is not valid.");
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
		return flag;
	}

	private static void SignXml(XmlDocument Doc, RSA Key)
	{
		if (Doc == null)
		{
			throw new ArgumentException("Doc");
		}
		if (Key == null)
		{
			throw new ArgumentException("Key");
		}
		XmlNodeList elementsByTagName = Doc.GetElementsByTagName("Signature");
		if (elementsByTagName.Count > 0)
		{
			for (int num = elementsByTagName.Count - 1; num >= 0; num--)
			{
				elementsByTagName[num].ParentNode.RemoveChild(elementsByTagName[num]);
			}
		}
		SignedXml signedXml = new SignedXml(Doc);
		signedXml.SigningKey = Key;
		Reference reference = new Reference();
		reference.Uri = "";
		XmlDsigEnvelopedSignatureTransform transform = new XmlDsigEnvelopedSignatureTransform();
		reference.AddTransform(transform);
		signedXml.AddReference(reference);
		signedXml.ComputeSignature();
		XmlElement xml = signedXml.GetXml();
		Doc.DocumentElement.AppendChild(Doc.ImportNode(xml, deep: true));
	}

	private static bool VerifyXml(XmlDocument Doc, RSA Key)
	{
		if (Doc == null)
		{
			throw new ArgumentException("Doc");
		}
		if (Key == null)
		{
			throw new ArgumentException("Key");
		}
		SignedXml signedXml = new SignedXml(Doc);
		XmlNodeList elementsByTagName = Doc.GetElementsByTagName("Signature");
		if (elementsByTagName.Count <= 0)
		{
			throw new CryptographicException("Verification failed: No Signature was found in the document.");
		}
		if (elementsByTagName.Count >= 2)
		{
			throw new CryptographicException("Verification failed: More that one signature was found for the document.");
		}
		signedXml.LoadXml((XmlElement)elementsByTagName[0]);
		return signedXml.CheckSignature(Key);
	}
}
