using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using HIVECOMKERNELLib;
using QC.QsprShared.Dialogs;
using QC.QsprShared.Trace;
using QC.QsprTestObjects.Loops;
using QC.QsprTestObjects.Parameters;
using QC.QsprTestObjects.Tests.Base;

namespace QC.QsprTestObjects.Tests.Hive;

[Serializable]
public class HiveTest : BaseTest
{
	private HiveTestProperties HiveTestProperties = new HiveTestProperties();

	private HKernel HiveKernel => Root.Scheduler.KernelMgr.HiveKernel;

	[XmlIgnore]
	[TypeConverter(typeof(ParamCollectionConverter))]
	public override TestProperties Properties
	{
		get
		{
			HiveTestProperties.Owner = this;
			return HiveTestProperties;
		}
		set
		{
			HiveTestProperties = (HiveTestProperties)value;
			HiveTestProperties.Owner = this;
		}
	}

	public HiveTestProperties HiveProperties
	{
		get
		{
			return HiveTestProperties;
		}
		set
		{
			HiveTestProperties = value;
		}
	}

	public HiveTest()
	{
	}

	public HiveTest(string name, string targetName, RootTest root)
		: base(name, targetName, root)
	{
		TraceMessage.Write(ToString(), "Constructor: " + name, TraceMessageType.Trace);
	}

	public override BaseTest Clone()
	{
		HiveTest hiveTest = new HiveTest();
		hiveTest.Properties = Properties.Clone();
		base.Copy(hiveTest);
		return hiveTest;
	}

	public static void ShutdownKernel()
	{
	}

	public static bool Options()
	{
		AppMessageDialog.Show("Options Not applicable for SUITE tests.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Information);
		return false;
	}

	public override void GetAllParamInfo(string realName, string containerName, ref object objParameters)
	{
		HiveKernel.GetAllParamInfo(realName, ref objParameters);
		try
		{
			object[,] array = (object[,])objParameters;
			for (int i = 0; i < array.GetLength(1); i++)
			{
				if (((int)array[10, i] & 0x400) == 1024)
				{
					try
					{
						string text = (string)array[9, i];
						if (text != null && text.Length > 1)
						{
							string[] array2 = text.Split(';');
							if (array.GetLength(0) > 13)
							{
								array[14, i] = array2[0];
							}
							if (array2.Length > 1)
							{
								array[9, i] = text.Remove(0, text.IndexOf(';') + 1);
							}
							else
							{
								array[9, i] = "";
							}
						}
					}
					catch (Exception ex)
					{
						TraceMessage.Write("HiveKernel.GetAllParamInfo", ex.Message, TraceMessageType.Exception);
					}
				}
				array[1, i] = ChangeDataType(array[1, i].ToString());
				if (((int)array[10, i] & 2) == 2)
				{
					try
					{
						string text2 = (string)array[9, i];
						string text3 = "";
						if (text2 != null && text2.Length > 1)
						{
							string[] array3 = text2.Split(';');
							for (int num = array3.GetLength(0); num > 1; num--)
							{
								text3 = text3 + array3[num - 1] + ";";
							}
							text3 += array3[0];
						}
						array[9, i] = text3;
					}
					catch (Exception)
					{
					}
				}
				if (((int)array[10, i] & 0x100) != 256)
				{
					_ = (int)array[10, i];
					if (false)
					{
						continue;
					}
				}
				try
				{
					if (!(array[1, i].ToString() != "str"))
					{
						continue;
					}
					try
					{
						string text4 = ((string)array[9, i]).Trim();
						string revCons = "";
						if (text4 == null || text4.Length <= 1)
						{
							continue;
						}
						if (text4.EndsWith(";"))
						{
							text4 = text4.TrimEnd(';');
						}
						string[] array4 = text4.Split(';');
						if (array4.Length > 1)
						{
							if (!IsSequenceAssigned(array4, out revCons))
							{
								revCons = ((((int)array[10, i] & 0x2000) != 8192 && ((int)array[10, i] & 0x3000) != 12288 && ((int)array[10, i] & 0x1000) != 4096 && ((int)array[10, i] & 2) != 2) ? ReverseConstraints(array4) : array[9, i].ToString());
							}
							array[10, i] = 8;
							if (revCons.Length > 0)
							{
								array[9, i] = revCons;
							}
						}
					}
					catch (Exception ex3)
					{
						TraceMessage.Write("HiveKernel.GetAllParamInfo", "Error while reversing constraints " + ex3.Message, TraceMessageType.Exception);
					}
				}
				catch (Exception ex4)
				{
					TraceMessage.Write(ToString(), "GetAllParamInfo reverse constraints failed, " + ex4.Message, TraceMessageType.Exception);
				}
			}
			objParameters = array;
		}
		catch (Exception ex5)
		{
			TraceMessage.Write(ToString(), "GetAllParamInfo failed, " + ex5.Message, TraceMessageType.Exception);
		}
	}

	private static string ReverseConstraints(string[] splittedConstraints)
	{
		StringBuilder stringBuilder = new StringBuilder();
		foreach (string text in splittedConstraints)
		{
			char[] separator = new char[5] { '=', ',', '.', ':', '-' };
			string[] array = text.Trim().Split(separator);
			string[] array2 = text.Trim().Split(' ');
			if (array.GetLength(0) > 1)
			{
				string text2 = text.Trim().Remove(0, array[0].Length + 1);
				stringBuilder.Append(text2.Trim() + "=" + array[0] + ";");
				continue;
			}
			if (array2.GetLength(0) > 1)
			{
				string text3 = text.Trim().Remove(0, array2[0].Length + 1);
				stringBuilder.Append(text3.Trim() + "=" + array2[0] + ";");
				continue;
			}
			return "";
		}
		return stringBuilder.ToString();
	}

	private bool IsSequenceAssigned(string[] constraints, out string revCons)
	{
		revCons = "";
		StringBuilder stringBuilder = new StringBuilder();
		foreach (string text in constraints)
		{
			if (text.Trim().Length > 4 && int.TryParse(text.Trim().Substring(0, 4), out var result))
			{
				stringBuilder.Append(FormatConstraints(result, text.Trim().Substring(4)));
				continue;
			}
			if (text.Trim().Length > 3 && int.TryParse(text.Trim().Substring(0, 3), out result))
			{
				stringBuilder.Append(FormatConstraints(result, text.Trim().Substring(3)));
				continue;
			}
			if (text.Trim().Length > 2 && int.TryParse(text.Trim().Substring(0, 2), out result))
			{
				stringBuilder.Append(FormatConstraints(result, text.Trim().Substring(2)));
				continue;
			}
			if (text.Trim().Length > 1 && int.TryParse(text.Trim().Substring(0, 1), out result))
			{
				stringBuilder.Append(FormatConstraints(result, text.Trim().Substring(1)));
				continue;
			}
			return false;
		}
		revCons = stringBuilder.ToString();
		return true;
	}

	private string FormatConstraints(int elementPart, string namePart)
	{
		namePart = namePart.Trim();
		if (namePart.Substring(0, 1) == "=" || namePart.Substring(0, 1) == "," || namePart.Substring(0, 1) == "." || namePart.Substring(0, 1) == ":" || namePart.Substring(0, 1) == "-")
		{
			namePart = namePart.Remove(0, 1);
		}
		return namePart.Trim() + "=" + elementPart + ";";
	}

	private string ChangeDataType(string dataType)
	{
		switch ((eHIVEK_Type)Enum.Parse(typeof(eHIVEK_Type), dataType))
		{
		case eHIVEK_Type.hivekWORD:
		case eHIVEK_Type.hivekINT:
		case eHIVEK_Type.hivekHEX:
		case eHIVEK_Type.hivekOCT:
		case eHIVEK_Type.hivekBOOL:
			return "int";
		case eHIVEK_Type.hivekDOUBLE:
			return "double";
		case eHIVEK_Type.hivekSTRING:
			return "str";
		default:
			return "str";
		}
	}

	public override void GetResultsParamInfo(ref object obj)
	{
		HiveKernel.GetResultsParamInfo(ref obj);
	}

	public override bool StartTest()
	{
		TraceMessage.Write(ToString(), "StartTest: " + Properties.TestName, TraceMessageType.Trace);
		try
		{
			if (!LoadContainer())
			{
				AppMessageDialog.Show("HiveTest: " + Properties.TestName + " not found.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
				ExceptionHandle("HiveTest: " + Properties.TestName + " not found.");
				return false;
			}
			object[,] array = new object[Properties.Parameters.Count + 1, 5];
			int num = 0;
			foreach (ParameterCls parameter in Properties.Parameters)
			{
				string gvReplacedValue = ParameterCollection.GetGvReplacedValue(Root.Scheduler, parameter.Value);
				array[num, 0] = parameter.Name;
				array[num, 1] = gvReplacedValue;
				array[num, 2] = parameter.LowerLimit;
				array[num, 3] = parameter.UpperLimit;
				array[num, 4] = parameter.NoOfElements;
				num++;
			}
			array[num, 0] = "Bookkeeping";
			array[num, 1] = (Properties.BookKeeping ? "1" : "0");
			array[num, 2] = "0";
			array[num, 3] = "0";
			array[num, 4] = 1;
			object objParameters = array;
			object[] array2 = new object[2];
			if (Properties.DescriptionName.Trim() == "")
			{
				((ScenarioHandler)Root.Scheduler.QTMData.scenarioHandler).Update(Root.Scheduler.GlobalStatus);
				Root.Scheduler.GlobalStatus.LoopDetails = Root.Scheduler.GlobalStatus.LoopDetailsComplete;
			}
			else
			{
				((ScenarioHandler)Root.Scheduler.QTMData.scenarioHandler).Update(Root.Scheduler.GlobalStatus);
			}
			string text = Properties.TestName;
			if (Properties.DescriptionName.Trim() != "")
			{
				text = Properties.DescriptionName.Trim();
			}
			array2[0] = text;
			array2[1] = Properties.TargetName;
			object objProperties = array2;
			Root.Scheduler.KernelMgr.StartNewSUITETest();
			RunTest(Properties.RealName, ref objParameters, ref objProperties);
		}
		catch
		{
		}
		return true;
	}

	public override void RunQTMTest(string testName, string containerName, ref object objParameters, ref object objProperties)
	{
		Root.Scheduler.KernelMgr.SendGlobalVarsToHive(sendAll: false);
		Root.Scheduler.KernelMgr.HiveTestRunning = true;
		if (Root.Scheduler.GlobalStatus.SimulatorMode)
		{
			HiveKernel.RunTest("SimulationModeTest", ref objParameters, ref objProperties);
		}
		else
		{
			HiveKernel.RunTest(testName, ref objParameters, ref objProperties);
		}
	}

	public override void StopQTMTest()
	{
		HiveKernel.StopTest();
	}

	public HiveTest Copy(HiveTest b)
	{
		Properties = b.Properties;
		base.Copy(b);
		return this;
	}

	public override void Add(BaseTest baseTest)
	{
	}

	public override void Remove(BaseTest baseTest)
	{
	}

	public override void Display(int indent)
	{
	}

	public override void Insert(BaseTest baseTest, int index)
	{
	}
}
