using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Markup;
using QC.GlobalVariableManager;
using QC.QSPR;
using QC.QsprShared.Dialogs;
using QC.QsprShared.Trace;
using QC.QsprShared.Utilities;
using QC.QsprTestObjects.Tests.Base;
using QC.QTMApplication.Automation;
using QC.QTMApplication.Plugin.Common;
using QC.QTMInterface;
using QC.QTMInterface.Interfaces;
using QC.QTMSecurity;
using QsprMiscShared.Utilities;

namespace QC.QTMApplication;

public partial class WPFTestTreeWindowColl : System.Windows.Controls.UserControl, INotifyPropertyChanged, IComponentConnector
{
	public delegate void TTDPluginMenuDelegate(object sender, PluginMenuEventsArgs e);

	public delegate void HandleGenericMessageDelegate(string messageType, GenericTestData data, string pluginNames);

	public delegate void HandleGenericParamMessageDelegate(string messageType, string id, string name, string value, string units, string lowerLimit, string upperLimit, string pluginNames);

	public delegate void HandleCustomMessageDelegate(object customData, string pluginNames);

	public delegate void OnUpdateWindowBG(Color bgColor);

	private delegate CallbackResultInfo ProcessSpecialMessage_Delegate(TTDPluginEventArgs e);

	private struct PluginData
	{
		public ArrayList messageQueue;

		public TTDPlugIn testTreeForm;
	}

	private HandleGenericMessageDelegate genericMsgDel;

	private HandleGenericParamMessageDelegate genericParamMsgDel;

	private HandleCustomMessageDelegate customMsgDel;

	public OnUpdateWindowBG UpdateWindowBG;

	private Dictionary<string, TabItem> pluginTitleTabItemDictionary = new Dictionary<string, TabItem>();

	private AutomationHandler automationHandler;

	private Dictionary<string, TTDPlugIn> TTDPlugInsCollDictionary = new Dictionary<string, TTDPlugIn>();

	private Dictionary<TTDPlugIn, PluginMessenger> messengersByPlugin = new Dictionary<TTDPlugIn, PluginMessenger>();

	private WSpaceConfig wsc = default(WSpaceConfig);

	private bool registrationPluginLoaded;

	private bool treeInFocus;

	internal bool CloseHidesUI;

	public static TTDWpfTreeView TTDView;

	public Hashtable TTDPlugInsColl => new Hashtable(TTDPlugInsCollDictionary);

	public bool RegistrationPluginLoaded
	{
		get
		{
			return registrationPluginLoaded;
		}
		set
		{
			if (value != registrationPluginLoaded)
			{
				registrationPluginLoaded = value;
				RaiseOnPropertyChangedEvent("RegistrationPluginLoaded");
			}
		}
	}

	public bool TreeInFocus
	{
		get
		{
			return treeInFocus;
		}
		set
		{
			if (value != treeInFocus)
			{
				treeInFocus = value;
				RaiseOnPropertyChangedEvent("TreeInFocus");
			}
		}
	}

	public bool TreeChanged
	{
		get
		{
			return ttdWpfTreeView.TreeChanged;
		}
		set
		{
			ttdWpfTreeView.TreeChanged = value;
		}
	}

	public ArrayList AllPluginConfigInfo
	{
		get
		{
			ArrayList arrayList = new ArrayList();
			foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
			{
				arrayList.Add(value.PlugInConfigInfo);
			}
			return arrayList;
		}
		set
		{
			ArrayList arrayList = new ArrayList();
			arrayList = value;
			foreach (TTDPlugIn value2 in TTDPlugInsCollDictionary.Values)
			{
				ConfigInfo configInfo = new ConfigInfo();
				configInfo.PlugInConfigNames = new ArrayList();
				configInfo.PlugInConfigValues = new ArrayList();
				configInfo.PlugInName = value2.Name;
				value2.PlugInConfigInfo = configInfo;
			}
			foreach (ConfigInfo item in arrayList)
			{
				string plugInName = item.PlugInName;
				if (TTDPlugInsCollDictionary.ContainsKey(plugInName))
				{
					TTDPlugIn tTDPlugIn = TTDPlugInsCollDictionary[plugInName];
					if (tTDPlugIn != null)
					{
						tTDPlugIn.PlugInConfigInfo = item;
					}
				}
			}
		}
	}

	public Action<object> AutomationOnTestMessageRecieved { get; set; }

	public QSPRMainWindow QSPRWindow { get; set; }

	public event PropertyChangedEventHandler PropertyChanged;

	[Category("Plugins")]
	[Description("Will redirect menu messages to the parent container.")]
	public event TTDPluginMenuDelegate OnTTDPluginMenu;

	protected void RaiseOnPropertyChangedEvent(string propertyName)
	{
		if (this.PropertyChanged != null)
		{
			this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}
	}

	public WPFTestTreeWindowColl()
	{
		InitializeComponent();
		TTDView = ttdWpfTreeView;
		ttdWpfTreeView.LinkFileFound += OpenLinkedTree;
		TTDWpfTreeView tTDWpfTreeView = ttdWpfTreeView;
		tTDWpfTreeView.OnTestTreeFocusChanged = (TTDWpfTreeView.TestTreeFocusChanged)Delegate.Combine(tTDWpfTreeView.OnTestTreeFocusChanged, new TTDWpfTreeView.TestTreeFocusChanged(TreeFocusChanged));
		InitAutomation();
	}

	public void TreeFocusChanged(bool focused)
	{
		TreeInFocus = focused;
	}

	private void InitAutomation()
	{
		automationHandler = new AutomationHandler(this);
		automationHandler.NewTree = OnNewXMLTree;
		automationHandler.OpenFile = OpenFile;
		automationHandler.OnPluginMenuCmd = OnAutomationMenuCmd;
		automationHandler.HandleToolsClick = HandleToolsClick;
		automationHandler.GetTesterConfig = GetTesterConfiguration;
		automationHandler.GetCloseHidesUI = GetCloseHidesUI;
		automationHandler.SetCloseHidesUI = SetCloseHidesUI;
		automationHandler.SaveFile = ttdWpfTreeView.SaveFile;
		automationHandler.SaveAsFile = ttdWpfTreeView.SaveAsFile;
		automationHandler.AddFolder = ttdWpfTreeView.AddFolder;
		automationHandler.EndTestNameEdit = ttdWpfTreeView.TestTreeEditor.EndTestNameEdit;
		automationHandler.DeleteNode = ttdWpfTreeView.DeleteNode;
		automationHandler.ImportTestTree = ttdWpfTreeView.ImportTestTree;
		automationHandler.UpdateWindowBG = UpdateWindowBgColor;
		automationHandler.AddContainer = ttdWpfTreeView.AddContainer;
		automationHandler.AddTest = ttdWpfTreeView.AddTest;
		automationHandler.AddScriptParam = ttdWpfTreeView.AddScriptParameter;
		automationHandler.EnableLoopRow = ttdWpfTreeView.EnableLoopRow;
		automationHandler.EnableParamDataLogging = ttdWpfTreeView.EnableDataLogging;
		automationHandler.GetLoopValues = ttdWpfTreeView.GetLoopValues;
		automationHandler.ResetTestTree = ttdWpfTreeView.ResetTestTree;
		automationHandler.RegisterTree = RegisterTree;
		automationHandler.RunTest = ttdWpfTreeView.RunTest;
		automationHandler.RenameNode = ttdWpfTreeView.RenameNode;
		automationHandler.SetTestParamLimits = ttdWpfTreeView.SetTestParamLimits;
		automationHandler.SetTreeChanged = OnSetTreeChanged;
		automationHandler.SyncTest = ttdWpfTreeView.SyncTest;
		automationHandler.CopyTest = ttdWpfTreeView.CopyTest;
		automationHandler.ExportNodeToTextFile = ttdWpfTreeView.ExportNodeToTextFile;
	}

	private void OnSetTreeChanged(bool changed = true)
	{
		TreeChanged = changed;
		ttdWpfTreeView.TreeChangedDataCollection = changed;
	}

	internal CallbackResultInfo RegisterTree(TTDPluginEventArgs e, CallbackResultInfo cInfo)
	{
		try
		{
			RegisterTreeInfo registerTreeInfo = (RegisterTreeInfo)e.Message;
			string text = "RegisterTree;";
			if (!string.IsNullOrEmpty(registerTreeInfo.serverName))
			{
				text = text + "SERVER_NAME=" + registerTreeInfo.serverName;
			}
			if (!string.IsNullOrEmpty(registerTreeInfo.databaseName))
			{
				text = text + ";DB_NAME=" + registerTreeInfo.databaseName;
			}
			text = text + ";NO_DB=" + registerTreeInfo.registerWithoutDatabase;
			foreach (TTDPlugIn value in TTDPlugInsColl.Values)
			{
				if (value.Name == "Registration")
				{
					value.XmlTreeName = ttdWpfTreeView.XmlTreeName;
				}
			}
			if (SendMenuMsgToPlugins(text))
			{
				cInfo.Result = true;
				cInfo.Message = "Tree registered";
			}
			else
			{
				cInfo.Result = false;
				cInfo.Message = "Failed to add register tree.";
			}
		}
		catch (Exception ex)
		{
			cInfo.Result = false;
			cInfo.Message = "Failed to add test script parameter. " + ex.Message + ex.InnerException;
		}
		return cInfo;
	}

	private void OpenLinkedTree(object sender, string LinkedTreeFileName, string linkedConfigFile)
	{
		if (!string.IsNullOrEmpty(linkedConfigFile))
		{
			UpdateGlobalVbleForLinkedTree(linkedConfigFile, out var _);
		}
	}

	public ArrayList UpdateGlobalVbleForLinkedTree(string ConfigFileName, out Dictionary<string, string> overwriteConfigs)
	{
		ArrayList arrayList = new ArrayList();
		overwriteConfigs = new Dictionary<string, string>();
		if (ConfigFileName != "")
		{
			try
			{
				arrayList = GetTesterConfigurationForLinkedTree(ConfigFileName);
				if (arrayList != null && arrayList.Count > 0)
				{
					foreach (TesterConfigurationInfo item in arrayList)
					{
						if (QTMGlobalVariable.Contains(item.Name))
						{
							if (!item.OverwriteWhenLinked && ttdWpfTreeView._scheduler.GlobalStatus.TestRunning)
							{
								QTMGlobalVariable.GetGlobalVariable(item.Name, out var gvValue);
								if (gvValue != null && !overwriteConfigs.ContainsKey(item.Name))
								{
									overwriteConfigs.Add(item.Name, gvValue);
								}
								ttdWpfTreeView._scheduler.Registry.SetGlobalVariable(item.Name, item.Value);
							}
						}
						else
						{
							ttdWpfTreeView._scheduler.Registry.SetGlobalVariable(item.Name, item.Value);
						}
					}
				}
			}
			catch (Exception ex)
			{
				TraceMessage.Write("QC.QTMApplication.WPFTestTreeWindowColl", "UpdateGlobalVbleForLinkedTree " + ex.Message, TraceMessageType.Exception);
			}
		}
		return arrayList;
	}

	private void UpdateWindowBgColor(Color color)
	{
		if (UpdateWindowBG != null)
		{
			UpdateWindowBG(color);
		}
	}

	private bool GetCloseHidesUI()
	{
		return CloseHidesUI;
	}

	private void SetCloseHidesUI(bool hide)
	{
		CloseHidesUI = hide;
	}

	private void OnAutomationMenuCmd(object sender, string menuKey)
	{
		if (this.OnTTDPluginMenu != null)
		{
			this.OnTTDPluginMenu(sender, new PluginMenuEventsArgs(menuKey));
		}
	}

	public void OnConfigInfo(WSpaceConfig wsc)
	{
		this.wsc = wsc;
		if (ttdWpfTreeView != null)
		{
			ttdWpfTreeView.OnConfigInfo(this.wsc);
		}
		foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
		{
			value.OnConfigInfo(this.wsc);
		}
	}

	public void OnCustomMessage(object messageData, string pluginNames)
	{
	}

	public void OnGenericMessage(string messageType, GenericTestData data, string pluginNames)
	{
	}

	public void OnGenericParamMessage(string messageType, string id, string name, string value, string units, string lowerLimit, string upperLimit, string pluginNames)
	{
	}

	public void OnDebugMsg(DebugMsgType msgType, object msgInfo)
	{
		foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
		{
			if (value.GetDebugMsg)
			{
				value.OnDebugMsg(msgType, msgInfo);
			}
		}
	}

	public void AddTTDPlugIn(TTDPlugIn dWin)
	{
		_ = wpfTestTreeTabControl.SelectedItem;
		TabItem tabItem = new TabItem();
		tabItem.Header = dWin.Caption;
		QTMUtility.LoadPluginContainer(tabItem, dWin);
		AddTabItem(tabItem);
		TTDPlugInsCollDictionary.Add(dWin.Caption, dWin);
		TTDView._scheduler.GlobalStatus.PluginList.Add(dWin.Caption);
		if (dWin.Caption == "Registration")
		{
			RegistrationPluginLoaded = true;
		}
		dWin.OnTTDPluginHandler = OnTTDPluginHandler;
		dWin.OnConfigInfo(wsc);
		messengersByPlugin.Add(dWin, new PluginMessenger(dWin));
		if (dWin is IAutomationPlugin)
		{
			AutomationOnTestMessageRecieved = ((IAutomationPlugin)dWin).OnTestMessageRecieved;
		}
		if (wpfTestTreeTabControl.SelectedItem == null && pluginTitleTabItemDictionary.Count > 0)
		{
			TabItem selectedItem = pluginTitleTabItemDictionary.Values.FirstOrDefault();
			wpfTestTreeTabControl.SelectedItem = selectedItem;
		}
		if (dWin.Caption == QSPRWindow.WConfig.StartUpTTDPlugin)
		{
			wpfTestTreeTabControl.SelectedItem = tabItem;
		}
	}

	private void AddTabItem(TabItem tabItem)
	{
		wpfTestTreeTabControl.Items.Add(tabItem);
		pluginTitleTabItemDictionary.Add((string)tabItem.Header, tabItem);
	}

	public void HandleToolsClick(string menu)
	{
		try
		{
			switch (menu)
			{
			case "New":
				OnNewXMLTree(menu);
				break;
			case "Open":
				OpenFileMenu();
				break;
			case "Stop Tree":
				SendMenuMsgToPlugins(menu);
				break;
			case "Run Tree":
			case "Rerun":
				SendMenuMsgToPlugins(menu);
				break;
			case "SaveAs":
				if (!SendMenuMsgToPlugins(menu))
				{
					break;
				}
				{
					foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
					{
						value.XmlTreeName = ttdWpfTreeView.XmlTreeName;
					}
					break;
				}
			case "Save":
			case "Save as Test Plan":
			case "Cut":
			case "Copy":
			case "Paste":
			case "Delete":
			case "Add Script":
			case "Run Test":
			case "Loop Setup":
			case "Add DLL":
			case "Load DLL":
			case "UnLoad DLL":
			case "Delete DLL":
			case "New Folder":
			case "Stop Test":
			case "Show Parameters":
			case "Synchronize":
			case "Exit":
			case "Reset Tree Icons":
			case "Reset Test/Folder Icons":
			case "Reset All":
			case "Restore Window Layout":
			case "Restore Customized Layout":
			case "Save As Customized Layout":
			case "Save Current Docking":
			case "Abort":
			case "Resume":
			case "Pause":
			case "Simulation Mode":
			case "Run Setup Tests":
			case "Enable All Breakpoints":
			case "Disable All Breakpoints":
			case "DeleteAllBreakpoints":
			case "Enable All Logging":
			case "Disable All Logging":
			case "Search":
			case "SearchSetting":
			case "Restore Current Docking":
			case "QTM Loaded":
				SendMenuMsgToPlugins(menu);
				break;
			case "QSPR2.0 Window Layout":
			case "Tree Edit Mode Layout":
				if (wpfTestTreeTabControl.SelectedItem == null && pluginTitleTabItemDictionary.Count > 0)
				{
					TabItem selectedItem = pluginTitleTabItemDictionary.Values.FirstOrDefault();
					wpfTestTreeTabControl.SelectedItem = selectedItem;
				}
				SendMenuMsgToPlugins(menu);
				break;
			default:
				if (menu.EndsWith("Menu##Item"))
				{
					string fileName = menu.Replace("Menu##Item", "");
					OpenFile(fileName);
				}
				if (menu.Trim().IndexOf("#####") != -1)
				{
					ProcessPluginMessage(menu.Trim());
				}
				break;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "HandleToolsClick " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ProcessPluginMessage(string msg)
	{
		string[] array = msg.Split("#####"[0]);
		string text = array[0];
		string menuMessage = msg.Replace(text + "#####", "");
		if (TTDPlugInsColl.ContainsKey(text))
		{
			((TTDPlugIn)TTDPlugInsColl[text]).MenuMessages(menuMessage);
		}
	}

	public void OnNewXMLTree(string menu)
	{
		try
		{
			if (ttdWpfTreeView.TreeChanged && !QSecurity.LockedQGroup)
			{
				switch (AppMessageDialog.Show("Do you want to save the Test Tree?", "QSPR - Message Center", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, DialogResult.No, MessageDialogType.UIWarning))
				{
				case DialogResult.Cancel:
					return;
				case DialogResult.Yes:
					ttdWpfTreeView.SaveFile(SaveAsFormat.None);
					break;
				}
			}
			if (!ttdWpfTreeView.MenuMessages(menu))
			{
				return;
			}
			foreach (TTDPlugIn value in TTDPlugInsColl.Values)
			{
				value.XmlTreeName = "";
				value.MenuMessages(menu);
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show(ex.Message, DialogResult.OK, MessageDialogType.Exception);
		}
	}

	public ArrayList GetTesterConfiguration()
	{
		TraceMessage.Write(ToString(), "GetTesterConfiguration", TraceMessageType.Trace);
		try
		{
			ArrayList arrayList = new ArrayList();
			Hashtable hashtable = new Hashtable();
			RootTest root = TTDView.Root;
			string testerConfgiFile = PathUtils.ConvertToAbsolute(TTDView.TreeName, root.RootProperties.ConfigFileName);
			foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
			{
				ArrayList configuration = value.GetConfiguration(testerConfgiFile, root.RootProperties.RefreshConfig);
				if (configuration == null)
				{
					continue;
				}
				foreach (TesterConfigurationInfo item in configuration)
				{
					arrayList.Add(item);
					if (hashtable.ContainsKey(item.Name))
					{
						AppMessageDialog.Show($"Test config: {item.Name} is duplicated. First value will be used.\n Please update your tester configuration file to avoid this message. ", DialogResult.OK, MessageDialogType.Information);
					}
					else
					{
						hashtable.Add(item.Name, item);
					}
				}
			}
			ArrayList linkedFolders = new ArrayList();
			root.FindAllLinkedFolders(root, ref linkedFolders);
			foreach (FolderTest item2 in linkedFolders)
			{
				string testerConfgiFile2 = PathUtils.ConvertToAbsolute(TTDView.TreeName, item2.FolderProperties.ConfigLocation);
				foreach (TTDPlugIn value2 in TTDPlugInsCollDictionary.Values)
				{
					ArrayList configuration2 = value2.GetConfiguration(testerConfgiFile2, root.RootProperties.RefreshConfig);
					if (configuration2 == null)
					{
						continue;
					}
					foreach (TesterConfigurationInfo item3 in configuration2)
					{
						if (!hashtable.ContainsKey(item3.Name))
						{
							hashtable.Add(item3.Name, item3);
							arrayList.Add(item3);
						}
					}
				}
			}
			return arrayList;
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("GetTesterConfiguration failed, " + ex.Message, DialogResult.OK, MessageDialogType.Exception);
			TraceMessage.Write(ToString(), "GetTesterConfiguration " + ex.Message, TraceMessageType.Exception);
		}
		return null;
	}

	private bool SendMenuMsgToPlugins(string menu)
	{
		bool flag = ttdWpfTreeView.MenuMessages(menu);
		if (flag)
		{
			foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
			{
				value.MenuMessages(menu);
			}
		}
		return flag;
	}

	private void OpenFileMenu()
	{
		OpenFileDialog openFileDialog = new OpenFileDialog();
		openFileDialog.Filter = "QSPR test tree files (*.cxtt, *.xtt)|*.cxtt;*.xtt|All files (*.*)|*.*";
		if (string.IsNullOrWhiteSpace(TTDView.TreeDisplayName) || TTDView.TreeDisplayName.ToLower().EndsWith(".cxtt"))
		{
			openFileDialog.FilterIndex = 1;
		}
		else
		{
			openFileDialog.FilterIndex = 2;
		}
		openFileDialog.RestoreDirectory = true;
		if (openFileDialog.ShowDialog() == DialogResult.OK)
		{
			OpenFile(openFileDialog.FileName);
		}
	}

	private CallbackResultInfo OnTTDPluginHandler(object sender, TTDPluginEventArgs e)
	{
		CallbackResultInfo result = default(CallbackResultInfo);
		try
		{
			switch (e.MessageCategory)
			{
			case CallbackCategory.MENU_MESSAGE:
				if (e.Key == "Exit")
				{
					CloseHidesUI = false;
				}
				if (this.OnTTDPluginMenu != null)
				{
					this.OnTTDPluginMenu(this, new PluginMenuEventsArgs(e.Key));
				}
				result.Result = true;
				break;
			case CallbackCategory.SPECIAL_MESSAGE:
				if (e.Key == "Registration Begin")
				{
					HandleRegistrationMessage();
					result.Result = true;
					break;
				}
				if (e.Key == "Registration End")
				{
					HandleAfterRegistrationMessage();
					result.Result = true;
					break;
				}
				result = ProcessSpecialMessage(e);
				return result;
			}
		}
		catch (Exception ex)
		{
			result.Message = ex.Message;
			result.Result = false;
		}
		return result;
	}

	private void WPFTestTreeWindowColl_Loaded(object sender, RoutedEventArgs e)
	{
		ttdWpfTreeView.OnConfigInfo(wsc);
		genericMsgDel = HandleGenericMsg;
	}

	public ArrayList GetTesterConfigurationForLinkedTree(string ConfigFileName)
	{
		string testerConfgiFile = PathUtils.ConvertToAbsolute(ttdWpfTreeView.XmlTreeName, ConfigFileName);
		TraceMessage.Write(ToString(), "GetTesterConfigurationForLinkedTree", TraceMessageType.Trace);
		try
		{
			ArrayList arrayList = new ArrayList();
			foreach (TTDPlugIn value2 in TTDPlugInsColl.Values)
			{
				if (!(value2.Caption == "Tester Configuration"))
				{
					continue;
				}
				ArrayList configuration = value2.GetConfiguration(testerConfgiFile, refresh: true);
				if (configuration == null)
				{
					continue;
				}
				foreach (TesterConfigurationInfo item in configuration)
				{
					arrayList.Add(item);
				}
			}
			return arrayList;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "GetTesterConfigurationForLinkedTree " + ex.Message, TraceMessageType.Exception);
		}
		return null;
	}

	private void HandleRegistrationMessage()
	{
		try
		{
			if (ttdWpfTreeView.TreeChanged || ttdWpfTreeView.XmlTreeName == "" || ttdWpfTreeView.XmlTreeName != ttdWpfTreeView.TreeDisplayName)
			{
				DialogResult dialogResult = AppMessageDialog.Show("Tree should be saved before continuing with registration.\nTree " + ttdWpfTreeView.TreeDisplayName + " would be saved!", "QSPR - Tree Registration", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, DialogResult.No, MessageDialogType.Warning);
				if (dialogResult == DialogResult.Cancel || dialogResult != DialogResult.OK)
				{
					return;
				}
				UpdateDLLVersions();
				if (!SendMenuMsgToPlugins("Save"))
				{
					return;
				}
				foreach (TTDPlugIn value in TTDPlugInsColl.Values)
				{
					value.XmlTreeName = ttdWpfTreeView.XmlTreeName;
				}
				SendMenuMsgToPlugins("RegisterTree");
				return;
			}
			FileInfo fileInfo = new FileInfo(ttdWpfTreeView.XmlTreeName);
			if (fileInfo.IsReadOnly)
			{
				AppMessageDialog.Show(ttdWpfTreeView.XmlTreeName + " is read only. Registration cannot be performed.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.CritialError);
				return;
			}
			if (ttdWpfTreeView.IsTreeRegistered)
			{
				RootTest root = TTDView.Root;
				DialogResult dialogResult2 = AppMessageDialog.Show("Tree is already registered at\n\nServer: " + root.RootProperties.Server + "\nDatabase: " + root.RootProperties.Database + "\n\nDo you want to  continue with the new registration?", "QSPR - Tree Registration", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.Warning);
				if (dialogResult2 != DialogResult.Yes)
				{
					return;
				}
				root.RemoveRegistrationInformation();
				UpdateDLLVersions();
				ttdWpfTreeView.MenuMessages("Save");
			}
			foreach (TTDPlugIn value2 in TTDPlugInsColl.Values)
			{
				value2.XmlTreeName = ttdWpfTreeView.XmlTreeName;
			}
			SendMenuMsgToPlugins("RegisterTree");
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show(ex.Message, DialogResult.OK, MessageDialogType.Exception);
		}
	}

	private void HandleAfterRegistrationMessage()
	{
		OpenFile(ttdWpfTreeView.XmlTreeName);
	}

	private void UpdateDLLVersions()
	{
		TTDView._scheduler.Registry.UpdateDLLVersions();
	}

	public void HandleGenericMsg(string messageType, GenericTestData data, string pluginNames)
	{
		try
		{
			ArrayList pluginRecipients = GetPluginRecipients(pluginNames);
			foreach (object item in pluginRecipients)
			{
				if (item is TTDPlugIn)
				{
					TTDPlugIn tTDPlugIn = (TTDPlugIn)item;
					tTDPlugIn.OnGenericMessage(messageType, data);
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "HandleGenericMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	private CallbackResultInfo ProcessSpecialMessage(TTDPluginEventArgs e)
	{
		CallbackResultInfo callbackResultInfo = default(CallbackResultInfo);
		try
		{
			TraceMessage.Write(ToString(), "ProcessSpecialMessage for " + e.Key, TraceMessageType.Trace);
			if (!(e.Key == "Run Tree"))
			{
				callbackResultInfo = SynchronousMethods(e, callbackResultInfo);
				return callbackResultInfo;
			}
			AsynchronousMethods(e);
			callbackResultInfo.Result = true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ProcessSpecialMessage failed, " + ex.Message, TraceMessageType.Exception);
		}
		return callbackResultInfo;
	}

	private CallbackResultInfo SynchronousMethods(TTDPluginEventArgs e, CallbackResultInfo cInfo)
	{
		if (this.InvokeRequired())
		{
			cInfo = (CallbackResultInfo)this.Invoke(new ProcessSpecialMessage_Delegate(ProcessSpecialMessage), new object[1] { e });
		}
		else
		{
			try
			{
				cInfo = automationHandler.SynchronousMethods(e);
			}
			catch (Exception ex)
			{
				cInfo.Message = ex.ToString();
				cInfo.Result = false;
			}
		}
		return cInfo;
	}

	private CallbackResultInfo AsynchronousMethods(TTDPluginEventArgs e)
	{
		CallbackResultInfo result = default(CallbackResultInfo);
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				AsynchronousMethods(e);
			});
		}
		else
		{
			try
			{
				result = automationHandler.AsynchronousMethods(e);
				return result;
			}
			catch (Exception ex)
			{
				AppMessageDialog.Show("Failed to execute " + e.Key + "; Error: " + ex.Message, DialogResult.OK, MessageDialogType.Exception);
				result.Message = ex.Message;
				result.Result = false;
			}
		}
		return result;
	}

	private ArrayList GetPluginRecipients(string pluginNames)
	{
		ArrayList arrayList = new ArrayList();
		try
		{
			string[] array = null;
			if (!string.IsNullOrEmpty(pluginNames))
			{
				array = pluginNames.Split(',');
			}
			foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
			{
				if (!(value is TTDPlugIn))
				{
					continue;
				}
				try
				{
					TTDPlugIn tTDPlugIn = value;
					if (array != null && array.Length > 0)
					{
						string[] array2 = array;
						foreach (string text in array2)
						{
							if (tTDPlugIn.Caption == text)
							{
								arrayList.Add(tTDPlugIn);
							}
						}
					}
					else
					{
						arrayList.Add(tTDPlugIn);
					}
				}
				catch (Exception ex)
				{
					TraceMessage.Write(ToString(), "GetPluginRecipients " + ex.Message, TraceMessageType.Trace);
				}
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "GetPluginRecipients " + ex2.Message, TraceMessageType.Exception);
		}
		return arrayList;
	}

	public void OpenFile(string fileName)
	{
		try
		{
			if (ttdWpfTreeView.TreeChanged && !QSecurity.LockedQGroup)
			{
				if (QSecurity.IsEngineer)
				{
					DialogResult dialogResult = AppMessageDialog.Show("Do you want to save " + ttdWpfTreeView.TreeDisplayName + " ?", "QSPR - Message Center", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, DialogResult.No, MessageDialogType.UIWarning);
					if (dialogResult == DialogResult.Cancel)
					{
						return;
					}
					if (dialogResult != DialogResult.Yes)
					{
					}
				}
				else if (QSecurity.IsTechnician)
				{
					DialogResult dialogResult2 = AppMessageDialog.Show("Tree  " + ttdWpfTreeView.TreeDisplayName + " can not be saved in Technician mode. Do you want to proceed? ", "QSPR - Message Center", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, DialogResult.Yes, MessageDialogType.CriticalWarning);
					if (dialogResult2 == DialogResult.No)
					{
						return;
					}
				}
			}
			if (!File.Exists(fileName))
			{
				AppMessageDialog.Show("File could not be found.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Error);
				return;
			}
			ttdWpfTreeView.XmlTreeName = fileName;
			if (!ttdWpfTreeView.MenuMessages("Open"))
			{
				return;
			}
			QSPRWindow.AddRecentFile(ttdWpfTreeView.TreeDisplayName);
			QTMGlobalVariable.SetGlobalVariable("TreeFileName", ttdWpfTreeView.TreeDisplayName);
			Analytics.WriteAnalytics("OpenTree", ttdWpfTreeView.TreeDisplayName);
			foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
			{
				value.XmlTreeName = fileName;
				value.MenuMessages("Open");
			}
			QSPRWindow.UpdateGlobalVble(GetFromTesterConfig: true);
			ttdWpfTreeView.MenuMessages("Refresh");
		}
		catch
		{
		}
	}

	public void AddTestCasesPlugIn(TestCasesPlugin dWin)
	{
		try
		{
			ttdWpfTreeView.AddTestCasesPlugin(dWin);
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show(ex.Message, DialogResult.OK, MessageDialogType.Exception);
		}
	}

	public void AddParamPlugIn(ParamViewPlugIn dWin)
	{
		try
		{
			ttdWpfTreeView.AddParamPlugIn(dWin);
		}
		catch
		{
		}
	}

	private void ttdWpfTreeView_FirstSelectedTestChanged(object sender, RoutedPropertyChangedEventArgs<BaseTest> e)
	{
	}

	public void OnMsg(ArrayList messageQueue)
	{
		TraceMessage.Write(ToString(), "OnMsg", TraceMessageType.Trace);
		try
		{
			ttdWpfTreeView.OnMsg(messageQueue);
			foreach (TTDPlugIn value in TTDPlugInsCollDictionary.Values)
			{
				PluginData pluginData = default(PluginData);
				pluginData.messageQueue = (ArrayList)messageQueue.Clone();
				pluginData.testTreeForm = value;
				foreach (MsgData item in messageQueue)
				{
					if (item.msgType == TestMsgType.OnUnitEnd)
					{
						TraceMessage.WriteAlways(ToString(), "Sending on unit end message to  plugin:" + value.Caption, TraceMessageType.Trace);
					}
				}
				messengersByPlugin[value].SendMsg(pluginData.messageQueue);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void LoadPluginToolbars()
	{
		List<string> list = new List<string>();
		foreach (TTDPlugIn value in TTDPlugInsColl.Values)
		{
			if (value.ToolbarItems != null)
			{
				list.Add(value.Caption.Trim());
			}
		}
		foreach (TTDPlugIn value2 in TTDPlugInsColl.Values)
		{
			if (value2.ToolbarItems == null)
			{
				continue;
			}
			value2.Caption.Trim();
			if (value2.ToolImages != null)
			{
				_ = value2.ToolbarItems.Count;
				_ = value2.ToolImages.Images.Count;
			}
			foreach (string toolbarItem in value2.ToolbarItems)
			{
				_ = value2.Caption.Trim() + "#####" + toolbarItem;
			}
		}
	}

	public bool Closing()
	{
		if (QSecurity.UserAccessLevel == AccessLevel.Engineer && ttdWpfTreeView.TreeChanged && !QSecurity.LockedQGroup)
		{
			switch (AppMessageDialog.Show("Do you want to save the Test Tree?", "QSPR - Message Center", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, DialogResult.No, MessageDialogType.UIWarning))
			{
			case DialogResult.Cancel:
				return false;
			case DialogResult.Yes:
				if (ttdWpfTreeView.SaveFile(SaveAsFormat.None))
				{
					return true;
				}
				return false;
			}
		}
		foreach (TTDPlugIn value in TTDPlugInsColl.Values)
		{
			try
			{
				if (!value.Closing())
				{
					return false;
				}
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "Closing " + ex.Message, TraceMessageType.Exception);
			}
		}
		return true;
	}

	public void ExpandTestTreeProperties()
	{
		ttdWpfTreeView.ExpandTreeProperties();
	}

	public void CollpaseTestTreeProperties()
	{
		ttdWpfTreeView.CollapseTreeProperties();
	}

	public bool IsSafeToExit()
	{
		foreach (TTDPlugIn value in TTDPlugInsColl.Values)
		{
			if (!value.IsSafeToExit)
			{
				return false;
			}
		}
		return true;
	}
}
