using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using QC.GlobalVariableManager;
using QC.QsprShared.Dialogs;
using QC.QsprShared.Trace;
using QC.QsprShared.Utilities;
using QC.QsprTestObjects.Parameters;
using QC.QsprTestObjects.TestConditions;
using QC.QsprTestObjects.Tests.Base;
using QC.QsprTestObjects.Tests.TestCase;
using QC.QTMApplication.Parameters;
using QC.QTMApplication.Utilities;
using QC.QTMInterface;
using QC.QTMInterface.Business_Objects;
using QC.QTMSecurity;
using QsprMiscShared.Utilities;

namespace QC.QTMApplication;

public partial class TTDParameterView : System.Windows.Controls.UserControl, INotifyPropertyChanged, IComponentConnector, IStyleConnector
{
	public delegate void ParameterChangedDelegate(object sender, ParameterChangeEventArgs e);

	public delegate void DataLoggingChangedDelegate(object sender, CheckState newState);

	public delegate void RegistrationChangedDelegate(object sender, string cause);

	public const string PARAMETER_NAME = "Parameter_Name";

	public const string LOWER_LIMIT = "LL";

	public const string UPPER_LIMIT = "UL";

	public const string VALUE = "Value";

	public const string DATA_LOGGING = "Data_Logging";

	public const string DATA_LOGGING_ENABLED = "Data_Logging_Enabled";

	public const string DATA_LOGGING_DISABLED = "Data_Logging_Disabled";

	public const string LOGGING_CONDITION = "Logging_Condition";

	public const string CHARTING_ENABLED = "Reporting_Enabled";

	public const string CHARTING_DISABLED = "Charting_Disabled";

	public const string UNIT = "Unit";

	public const string DESCRIPTION = "Description";

	public const string GV_SET = "GV_Set";

	public const string GV_GET = "GV_Get";

	public const string GV_LL_GET = "GV_LL_Get";

	public const string GV_UL_GET = "GV_UL_Get";

	public const string PARENT_ID = "Parent_ID";

	public const string ROW_ID = "Row_ID";

	public const string PARAMETER_OBJECT = "Parameter_Object";

	public const string HAS_CHILDREN = "HasChildren";

	public const string HAS_DIFFERENT_VALUES = "HasDifferentValues";

	public const string HAS_GV_GET_VALUE = "HasGvGetValue";

	public const string HAS_GV_GET_LL = "HasGvGetLL";

	public const string HAS_GV_GET_UL = "HasGvGetUL";

	public const string DIFFERENT_VALUES = "DifferentValues";

	public const string IS_PARAM_READ_ONLY = "IsParamReadOnly";

	public const string IS_PARAM_EDITABLE = "IsParamEditable";

	public const string ALL = "All";

	public const string INPUT_PARAM_TABLE = "Input Parameters11";

	public const string OUTPUT_PARAM_TABLE = "Output Parameters";

	private ParameterViewUISettings uiSettings = new ParameterViewUISettings();

	private KeyActionCommand keyCommand;

	public static bool arrayEditedWithUI;

	private static bool updatingTextValues;

	private DataTable paramTableOutput;

	private DataTable paramTableInput;

	private Dictionary<string, paramRelation> inputParamRelations = new Dictionary<string, paramRelation>();

	private Dictionary<string, paramRelation> outputParamRelations = new Dictionary<string, paramRelation>();

	private DataSet paramDataSetInput = new DataSet();

	private DataSet paramDataSetOutput = new DataSet();

	private WSpaceConfig wsc = default(WSpaceConfig);

	private bool loadingParameters;

	private bool readOnly;

	private ParameterCollection parameters = new ParameterCollection();

	private bool isFolder;

	private bool controlsDisabled;

	private bool showParameters;

	private string testType = "";

	private string testContainerName = "";

	private string realName = "";

	private bool isLinkNode;

	private bool refreshInputParam = true;

	private string currTestPath = "";

	private FolderTest folderTest;

	private List<DuplicatedParam> originalDuplicatedParams = new List<DuplicatedParam>();

	private Dictionary<string, List<string>> modifiedParams = new Dictionary<string, List<string>>();

	private List<string> linkParams = new List<string>();

	private Dictionary<string, List<string>> paramsWithDifferentValues = new Dictionary<string, List<string>>();

	private ParameterCollection originalParameters = new ParameterCollection();

	private List<DuplicatedParam> duplicatedParams = new List<DuplicatedParam>();

	private bool showToolTips = true;

	private System.Windows.Controls.DataGrid mainInputDataGrid;

	private System.Windows.Controls.DataGrid mainOutputDataGrid;

	private List<NestedDataGridInfo> childInputDataGridList = new List<NestedDataGridInfo>();

	private List<NestedDataGridInfo> childOutputDataGridList = new List<NestedDataGridInfo>();

	private WPFTextBoxPopup textPopup;

	public KeyActionCommand KeyCommand => keyCommand;

	public bool ReadOnly
	{
		get
		{
			if (QSecurity.LockedQGroup)
			{
				return true;
			}
			if (IsApprovedTestCase())
			{
				return true;
			}
			return readOnly;
		}
		set
		{
			try
			{
				readOnly = value;
				OnPropertyChanged("ReadOnly");
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "ReadOnly " + ex.Message, TraceMessageType.Exception);
			}
		}
	}

	public bool ShowParameters
	{
		get
		{
			return showParameters;
		}
		set
		{
			showParameters = value;
			OnPropertyChanged("ShowParameters");
		}
	}

	public bool IsFolder
	{
		get
		{
			return isFolder;
		}
		set
		{
			isFolder = value;
			OnPropertyChanged("IsFolder");
			ShowParameters = !isFolder;
		}
	}

	public string TestType
	{
		get
		{
			return testType;
		}
		set
		{
			testType = value;
		}
	}

	public string TestContainerName
	{
		get
		{
			return testContainerName;
		}
		set
		{
			testContainerName = value;
		}
	}

	public string RealName
	{
		get
		{
			return realName;
		}
		set
		{
			realName = value;
		}
	}

	public bool IsLinkNode
	{
		get
		{
			return isLinkNode;
		}
		set
		{
			isLinkNode = value;
		}
	}

	public string CurrTestPath
	{
		set
		{
			if (!(value == currTestPath))
			{
				refreshInputParam = true;
			}
			currTestPath = value;
		}
	}

	public BaseTest Test { get; set; }

	public FolderTest FolderNode
	{
		set
		{
			folderTest = value;
			if (value != null && value is TestCaseTest)
			{
				ShowAllParameters();
			}
		}
	}

	public ParameterCollection Parameters
	{
		set
		{
			parameters = value;
			RefreshParamView();
		}
	}

	public DataView InputParamView => paramTableInput.DefaultView;

	public DataView OutputParamView => paramTableOutput.DefaultView;

	public event ParameterChangedDelegate OnParameterChanged;

	public event DataLoggingChangedDelegate OnDataLoggingChanged;

	public event RegistrationChangedDelegate OnRegistrationChanged;

	public event PropertyChangedEventHandler PropertyChanged;

	private bool IsApprovedTestCase()
	{
		if (IsFolder && folderTest != null && folderTest is TestCaseTest && (folderTest as TestCaseTest).TestCaseProperties.Status == ApprovalStates.Approved)
		{
			return true;
		}
		if (!IsFolder)
		{
			TestCaseTest testCase = Test.TestCase;
			if (testCase != null && testCase.TestCaseProperties.Status == ApprovalStates.Approved)
			{
				return true;
			}
		}
		return false;
	}

	public TTDParameterView()
	{
		InitializeComponent();
		base.DataContext = this;
		base.GotFocus += TTDParameterView_GotFocus;
		base.LostFocus += TTDParameterView_LostFocus;
		textPopup = new WPFTextBoxPopup();
		WPFTextBoxPopup wPFTextBoxPopup = textPopup;
		wPFTextBoxPopup.OnPreviewPopupKeyDown = (WPFTextBoxPopup.PreviewPopupKeyDown)Delegate.Combine(wPFTextBoxPopup.OnPreviewPopupKeyDown, new WPFTextBoxPopup.PreviewPopupKeyDown(TextBox_PreviewKeyDown));
		keyCommand = new KeyActionCommand(KeyCommand_Execute, KeyCommand_CanExecute);
		try
		{
			paramTableInput = GetInputTable("Input Parameters11");
			paramTableOutput = GetOutputTable("Output Parameters");
			textBoxParamName.Text = "";
			textBoxParamDescrip.Text = "";
			LoadLayout();
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "TTDParamView " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void TTDParameterView_LostFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.None;
	}

	private void TTDParameterView_GotFocus(object sender, RoutedEventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.ParameterView;
	}

	private void LoadLayout()
	{
		string settingsFilePath = GetSettingsFilePath();
		if (!File.Exists(settingsFilePath))
		{
			return;
		}
		try
		{
			uiSettings = QTMUtility.Deserialize<ParameterViewUISettings>(settingsFilePath);
			if (uiSettings == null)
			{
				uiSettings = new ParameterViewUISettings();
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "TTDParamView " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void KeyCommand_Execute(object parameter)
	{
		string key = parameter as string;
		toolBar_Clicked(key);
	}

	private bool KeyCommand_CanExecute(object parameter)
	{
		return true;
	}

	private void toolBar_Clicked(string key)
	{
		try
		{
			switch (key)
			{
			case "ShowAllParams":
				ShowAllParameters();
				break;
			case "UndoAllChanges":
				break;
			case "SwitchView":
				break;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ultraToolbarsManager1_ToolClick failed, " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void ShowAllParameters()
	{
		ShowParameters = true;
		parameters = new ParameterCollection();
		modifiedParams.Clear();
		paramsWithDifferentValues = new Dictionary<string, List<string>>();
		AddParamsForAllTests(folderTest);
		ParamsWithDifferentValues();
		originalParameters = parameters.Clone();
		LoadParameters();
	}

	private void AddParamsForAllTests(FolderTest folder)
	{
		foreach (BaseTest test in folder.TestList)
		{
			if (test is FolderTest)
			{
				AddParamsForAllTests((FolderTest)test);
				continue;
			}
			foreach (ParameterCls parameter in test.Properties.Parameters)
			{
				if (!parameters.HasParameter(parameter.Name))
				{
					parameters.Add(parameter);
				}
				else
				{
					duplicatedParams.Add(new DuplicatedParam(test.TestPath, parameter));
					originalDuplicatedParams.Add(new DuplicatedParam(test.TestPath, parameter.Clone()));
				}
				if (test.Properties.LinkNode)
				{
					bool? isLinkActive = test.Properties.IsLinkActive;
					if (isLinkActive.GetValueOrDefault() && isLinkActive.HasValue && !linkParams.Contains(parameter.Name))
					{
						linkParams.Add(parameter.Name);
					}
				}
			}
		}
	}

	private void ParamsWithDifferentValues()
	{
		try
		{
			foreach (DuplicatedParam duplicatedParam in duplicatedParams)
			{
				if (paramsWithDifferentValues.ContainsKey(duplicatedParam.Parameter.Name))
				{
					List<string> value = new List<string>();
					paramsWithDifferentValues.TryGetValue(duplicatedParam.Parameter.Name, out value);
					if (value != null && !value.Contains(duplicatedParam.Parameter.Value))
					{
						value.Add(duplicatedParam.Parameter.Value);
					}
				}
				else
				{
					List<string> list = new List<string>();
					list.Add(duplicatedParam.Parameter.Value);
					paramsWithDifferentValues.Add(duplicatedParam.Parameter.Name, list);
				}
			}
			foreach (ParameterCls parameter in parameters)
			{
				if (paramsWithDifferentValues.ContainsKey(parameter.Name))
				{
					List<string> value2 = new List<string>();
					paramsWithDifferentValues.TryGetValue(parameter.Name, out value2);
					if (value2 != null && !value2.Contains(parameter.Value))
					{
						value2.Add(parameter.Value);
					}
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "SetFlagForDifferentValues " + ex.Message, TraceMessageType.Exception);
		}
	}

	private DataTable GetInputTable(string tableName)
	{
		DataTable dataTable = new DataTable(tableName);
		dataTable.Columns.Add("Parameter_Name");
		dataTable.Columns.Add("Value");
		dataTable.Columns.Add("Data_Logging");
		dataTable.Columns.Add("Unit");
		dataTable.Columns.Add("Description");
		dataTable.Columns.Add("GV_Set");
		dataTable.Columns.Add("GV_Get");
		dataTable.Columns.Add("Parent_ID", typeof(int));
		dataTable.Columns.Add("Row_ID", typeof(int));
		dataTable.Columns.Add("Parameter_Object", typeof(ParameterCls));
		dataTable.Columns.Add("HasChildren", typeof(bool));
		dataTable.Columns.Add("HasDifferentValues", typeof(bool));
		dataTable.Columns.Add("DifferentValues");
		dataTable.Columns.Add("HasGvGetValue", typeof(bool));
		dataTable.Columns.Add("IsParamReadOnly", typeof(bool));
		dataTable.Columns.Add("IsParamEditable", typeof(bool));
		dataTable.PrimaryKey = new DataColumn[1] { dataTable.Columns["Row_ID"] };
		return dataTable;
	}

	private DataTable GetOutputTable(string tableName)
	{
		DataTable dataTable = new DataTable(tableName);
		dataTable.Columns.Add("Parameter_Name");
		dataTable.Columns.Add("LL");
		dataTable.Columns.Add("Value");
		dataTable.Columns.Add("UL");
		dataTable.Columns.Add("Data_Logging");
		dataTable.Columns.Add("Logging_Condition");
		dataTable.Columns.Add("Reporting_Enabled");
		dataTable.Columns.Add("Unit");
		dataTable.Columns.Add("Description");
		dataTable.Columns.Add("GV_Set");
		dataTable.Columns.Add("GV_Get");
		dataTable.Columns.Add("GV_LL_Get");
		dataTable.Columns.Add("GV_UL_Get");
		dataTable.Columns.Add("Parent_ID", typeof(int));
		dataTable.Columns.Add("Row_ID", typeof(int));
		dataTable.Columns.Add("Parameter_Object", typeof(ParameterCls));
		dataTable.Columns.Add("HasChildren", typeof(bool));
		dataTable.Columns.Add("HasDifferentValues", typeof(bool));
		dataTable.Columns.Add("DifferentValues");
		dataTable.Columns.Add("HasGvGetValue", typeof(bool));
		dataTable.Columns.Add("HasGvGetLL", typeof(bool));
		dataTable.Columns.Add("HasGvGetUL", typeof(bool));
		dataTable.Columns.Add("IsParamReadOnly", typeof(bool));
		dataTable.Columns.Add("IsParamEditable", typeof(bool));
		dataTable.PrimaryKey = new DataColumn[1] { dataTable.Columns["Row_ID"] };
		return dataTable;
	}

	public void OnConfigInfo(WSpaceConfig wConf)
	{
		try
		{
			wsc = wConf;
			showToolTips = wsc.ShowToolTips;
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "OnConfigInfo " + ex.Message, TraceMessageType.Exception);
		}
	}

	public void RefreshParamView()
	{
		modifiedParams.Clear();
		originalDuplicatedParams.Clear();
		if (originalParameters != null)
		{
			originalParameters.Clear();
		}
		duplicatedParams.Clear();
		paramsWithDifferentValues.Clear();
		linkParams.Clear();
		if (parameters != null)
		{
			ShowParameters = true;
			if (!isFolder || folderTest is TestCaseTest)
			{
				LoadParameters();
			}
		}
		else
		{
			ShowParameters = false;
			ultraGridOutput.Visibility = Visibility.Collapsed;
		}
	}

	private void LoadParameters()
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				LoadParameters();
			});
			return;
		}
		try
		{
			SaveCurrentDataGridSettings();
			ClearParameterDescriptionBox();
			loadingParameters = true;
			if (parameters != null)
			{
				ResetDataSources();
				if (refreshInputParam)
				{
					paramDataSetInput.Tables.Add(paramTableInput);
				}
				paramDataSetOutput.Tables.Add(paramTableOutput);
				paramTableInput.ColumnChanging -= paramTableInput_ColumnChanging;
				paramTableOutput.ColumnChanging -= paramTableOutput_ColumnChanging;
				foreach (ParameterCls parameter in parameters)
				{
					if (parameter.IsOutput)
					{
						AddOutputParam(parameter);
					}
					else if (parameter.IsInput && refreshInputParam)
					{
						AddInputParam(parameter);
					}
				}
				MarkParametersWithMultipleValues(paramTableInput);
				MarkParametersWithMultipleValues(paramTableOutput);
				BindDataSource();
				IsShowOutputGrid();
				paramTableInput.ColumnChanging += paramTableInput_ColumnChanging;
				paramTableOutput.ColumnChanging += paramTableOutput_ColumnChanging;
			}
			else
			{
				paramTableOutput.Clear();
				if (refreshInputParam)
				{
					paramTableInput.Clear();
				}
			}
			QSPRMainWindow.StatusBar.DebugMessage = "Parameters loaded.";
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show(string.Format("QC.QTMApplication.TTDParamView, Current Node " + ex.ToString()), DialogResult.OK, MessageDialogType.Exception);
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "CurrentNode " + ex.ToString(), TraceMessageType.Exception);
		}
		finally
		{
			loadingParameters = false;
		}
	}

	private void MarkParametersWithMultipleValues(DataTable tbl)
	{
		for (int i = 0; i < tbl.Rows.Count; i++)
		{
			if (tbl.Rows[i]["Parameter_Object"] is ParameterCls parameterCls && paramsWithDifferentValues.ContainsKey(parameterCls.Name))
			{
				List<string> value = new List<string>();
				paramsWithDifferentValues.TryGetValue(parameterCls.Name, out value);
				if (value != null && value.Count > 1)
				{
					tbl.Rows[i]["HasDifferentValues"] = true;
					tbl.Rows[i]["DifferentValues"] = string.Join("\n", value.ToArray());
				}
			}
		}
	}

	internal void SaveCurrentDataGridSettings()
	{
		if (mainInputDataGrid != null)
		{
			if (uiSettings.MainInputDataGridSettings == null)
			{
				uiSettings.MainInputDataGridSettings = new WPFDataGridSettings();
			}
			uiSettings.MainInputDataGridSettings.SaveGridSettings(mainInputDataGrid);
		}
		if (mainOutputDataGrid != null && mainOutputDataGrid.Items.Count > 0)
		{
			if (uiSettings.MainOutputDataGridSettings == null)
			{
				uiSettings.MainOutputDataGridSettings = new WPFDataGridSettings();
			}
			uiSettings.MainOutputDataGridSettings.SaveGridSettings(mainOutputDataGrid);
		}
	}

	private void UpdateParentIDs(DataSet ds, string mainTableName, Dictionary<string, paramRelation> relations)
	{
		foreach (DataTable table in ds.Tables)
		{
			if (!(table.TableName != mainTableName))
			{
				continue;
			}
			paramRelation value = null;
			relations.TryGetValue(table.TableName, out value);
			if (value == null)
			{
				continue;
			}
			foreach (DataRow row in table.Rows)
			{
				row["Parent_ID"] = value.ID;
			}
		}
	}

	private void CreateRelations(DataSet ds, string mainTableName, Dictionary<string, paramRelation> paramRelations)
	{
		UpdateParentIDs(ds, mainTableName, paramRelations);
		ArrayList arrayList = new ArrayList();
		foreach (DataTable table in ds.Tables)
		{
			if (!(table.TableName != mainTableName))
			{
				continue;
			}
			paramRelation value = null;
			paramRelations.TryGetValue(table.TableName, out value);
			if (value != null && string.IsNullOrEmpty(value.FolderName))
			{
				DataRelation relation = new DataRelation(table.TableName + DateTime.Now.Ticks, ds.Tables[mainTableName].Columns["Row_ID"], table.Columns["Parent_ID"], createConstraints: false);
				ds.Relations.Add(relation);
				DataRow[] array = ds.Tables[mainTableName].Select("Row_ID = " + value.ID);
				if (array.Length > 0)
				{
					array[0]["HasChildren"] = true;
				}
			}
			else if (value != null && !string.IsNullOrEmpty(value.FolderName) && ds.Tables.Contains(value.FolderName))
			{
				DataRelation relation2 = new DataRelation(table.TableName + DateTime.Now.Ticks, ds.Tables[value.FolderName].Columns["Row_ID"], table.Columns["Parent_ID"], createConstraints: false);
				ds.Relations.Add(relation2);
				DataRow[] array2 = ds.Tables[value.FolderName].Select("Row_ID = " + value.ID);
				if (array2.Length > 0)
				{
					array2[0]["HasChildren"] = true;
				}
			}
			else
			{
				ds.Tables[mainTableName].Merge(table);
				arrayList.Add(table.TableName);
			}
		}
		foreach (string item in arrayList)
		{
			ds.Tables.Remove(item);
		}
	}

	private void AddInputParam(ParameterCls pc)
	{
		try
		{
			if (!inputParamRelations.ContainsKey(pc.Name))
			{
				paramRelation paramRelation = new paramRelation();
				paramRelation.ID = inputParamRelations.Count;
				paramRelation.FolderName = pc.ParentName;
				inputParamRelations.Add(pc.Name, paramRelation);
			}
			if (!string.IsNullOrEmpty(pc.ParentName))
			{
				if (!paramDataSetInput.Tables.Contains(pc.ParentName))
				{
					paramDataSetInput.Tables.Add(GetInputTable(pc.ParentName));
				}
				DataRow row = paramDataSetInput.Tables[pc.ParentName].NewRow();
				CreateInputDataRow(pc, row);
				paramDataSetInput.Tables[pc.ParentName].Rows.Add(row);
			}
			else
			{
				DataRow row2 = paramTableInput.NewRow();
				CreateInputDataRow(pc, row2);
				paramTableInput.Rows.Add(row2);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), $"Failed to add input Parameter {pc.Name}. \nError Messages:{ex.Message} {ex.InnerException}\nPossible reason: Test has more than one parameter with the same name. ", TraceMessageType.Exception);
		}
	}

	private void AddOutputParam(ParameterCls pc)
	{
		try
		{
			if (!outputParamRelations.ContainsKey(pc.Name))
			{
				paramRelation paramRelation = new paramRelation();
				paramRelation.ID = outputParamRelations.Count;
				paramRelation.FolderName = pc.ParentName;
				outputParamRelations.Add(pc.Name, paramRelation);
			}
			if (!string.IsNullOrEmpty(pc.ParentName))
			{
				if (!paramDataSetOutput.Tables.Contains(pc.ParentName))
				{
					paramDataSetOutput.Tables.Add(GetOutputTable(pc.ParentName));
				}
				DataRow row = paramDataSetOutput.Tables[pc.ParentName].NewRow();
				CreateOutputDataRow(pc, row);
				paramDataSetOutput.Tables[pc.ParentName].Rows.Add(row);
			}
			else
			{
				DataRow row2 = paramTableOutput.NewRow();
				CreateOutputDataRow(pc, row2);
				paramTableOutput.Rows.Add(row2);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), $"Failed to add output Parameter {pc.Name}. \nError Messages:{ex.Message} {ex.InnerException}\nPossible reason: Test has more than one parameter with the same name. ", TraceMessageType.Exception);
		}
	}

	private bool IsShowOutputGrid()
	{
		if (paramTableOutput.Rows.Count > 0)
		{
			ultraGridOutput.Visibility = Visibility.Visible;
			return true;
		}
		ultraGridOutput.Visibility = Visibility.Collapsed;
		return false;
	}

	private void BindDataSource()
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				BindDataSource();
			});
			return;
		}
		if (refreshInputParam)
		{
			CreateRelations(paramDataSetInput, "Input Parameters11", inputParamRelations);
		}
		CreateRelations(paramDataSetOutput, "Output Parameters", outputParamRelations);
		BindDataSourceToGrid("InputGrid", ultraGridInput, paramTableInput);
		BindDataSourceToGrid("OutputGrid", ultraGridOutput, paramTableOutput);
	}

	private void BindDataSourceToGrid(string resourceKey, ContentControl contentControl, DataTable tbl)
	{
		DataTemplate dataTemplate = FindResource(resourceKey) as DataTemplate;
		ScrollViewer scrollViewer = dataTemplate.LoadContent() as ScrollViewer;
		System.Windows.Controls.DataGrid dataGrid = scrollViewer.Content as System.Windows.Controls.DataGrid;
		dataGrid.ItemsSource = tbl.DefaultView;
		dataGrid.Items.Refresh();
		contentControl.Content = scrollViewer;
		if (resourceKey == "InputGrid")
		{
			mainInputDataGrid = dataGrid;
			AttachToColumnWidthChangedProperty(dataGrid, MainInputGrid_ColumnWidthChanged);
		}
		else
		{
			mainOutputDataGrid = dataGrid;
			AttachToColumnWidthChangedProperty(dataGrid, MainOutputGrid_ColumnWidthChanged);
		}
		dataGrid.IsReadOnly = ReadOnly;
	}

	private void MainOutputGrid_ColumnWidthChanged(object sender, EventArgs e)
	{
		if (childOutputDataGridList.Count > 0)
		{
			SyncColumnWidthForChildGrids(childOutputDataGridList, mainOutputDataGrid);
		}
	}

	private void AttachToColumnWidthChangedProperty(System.Windows.Controls.DataGrid dataGrid, EventHandler columnWidthChangedEvent)
	{
		PropertyDescriptor propertyDescriptor = DependencyPropertyDescriptor.FromProperty(DataGridColumn.ActualWidthProperty, typeof(DataGridColumn));
		for (int i = 0; i < dataGrid.Columns.Count; i++)
		{
			propertyDescriptor.AddValueChanged(dataGrid.Columns[i], columnWidthChangedEvent);
		}
	}

	private void MainInputGrid_ColumnWidthChanged(object sender, EventArgs e)
	{
		if (childInputDataGridList.Count > 0)
		{
			SyncColumnWidthForChildGrids(childInputDataGridList, mainInputDataGrid);
		}
	}

	private void SyncColumnWidthForChildGrids(List<NestedDataGridInfo> childDataGridList, System.Windows.Controls.DataGrid mainDataGrid)
	{
		if (childDataGridList.Count <= 0 || mainDataGrid == null)
		{
			return;
		}
		for (int i = 0; i < mainDataGrid.Columns.Count; i++)
		{
			for (int j = 0; j < childDataGridList.Count; j++)
			{
				if (i == 1)
				{
					childDataGridList[j].Grid.Columns[i].Width = mainDataGrid.Columns[i].ActualWidth - (double)(10 * childDataGridList[j].Level);
				}
				else
				{
					childDataGridList[j].Grid.Columns[i].Width = mainDataGrid.Columns[i].ActualWidth;
				}
			}
		}
	}

	private void paramTableInput_ColumnChanging(object sender, DataColumnChangeEventArgs e)
	{
		ParameterCls parameterCls = e.Row["Parameter_Object"] as ParameterCls;
		if (e.Column.ColumnName == "Value")
		{
			string text = e.ProposedValue.ToString();
			string value = parameterCls.Value;
			bool isArray = ParameterCls.GetIsArray(parameterCls, IsDotNetTest(), realName, testContainerName);
			if (parameterCls.DataType != DataType.String)
			{
				text = text.Trim();
			}
			if (text.Trim().Replace("_\"_", "") != value.Trim().Replace("_\"_", ""))
			{
				if (parameterCls.DataType == DataType.Hex)
				{
					parameterCls.Value = int.Parse(text, NumberStyles.HexNumber).ToString();
				}
				else if (parameterCls.DataType == DataType.String && isArray)
				{
					parameterCls.Value = text;
					text = text.Replace("_\"_", "");
				}
				else
				{
					parameterCls.Value = text;
				}
				InformTreeViewWithChanges(parameterCls, "Value");
			}
		}
		else if (e.Column.ColumnName == "Description")
		{
			parameterCls.Description = e.ProposedValue.ToString();
			InformTreeViewWithChanges(parameterCls, "Description");
		}
		else if (e.Column.ColumnName == "Data_Logging")
		{
			if (e.ProposedValue != null)
			{
				if (e.ProposedValue.ToString() == bool.TrueString)
				{
					DataLoggingChanged(this, CheckState.Checked);
					InformTreeViewWithChanges(parameterCls, "Data_Logging_Enabled");
					parameterCls.bEnableDataLogging = true;
				}
				else if (e.ProposedValue.ToString() == bool.FalseString)
				{
					DataLoggingChanged(this, CheckState.Unchecked);
					InformTreeViewWithChanges(parameterCls, "Data_Logging_Disabled");
					parameterCls.bEnableDataLogging = false;
				}
			}
		}
		else if (e.Column.ColumnName == "Unit")
		{
			parameterCls.Unit = e.ProposedValue.ToString();
			InformTreeViewWithChanges(parameterCls, "Unit");
		}
		else if (e.Column.ColumnName == "GV_Get")
		{
			parameterCls.GlobalVariableName = e.ProposedValue.ToString();
			InformTreeViewWithChanges(parameterCls, "GV_Get");
			e.Row["HasGvGetValue"] = !string.IsNullOrWhiteSpace(e.ProposedValue.ToString());
		}
		else if (e.Column.ColumnName == "GV_Set")
		{
			parameterCls.GlobalVariableNameOther = e.ProposedValue.ToString();
			InformTreeViewWithChanges(parameterCls, "GV_Set");
		}
	}

	public static bool ValidateParameter(string newValue, string colName, DataType dType, bool isNullable)
	{
		try
		{
			if ((colName == "LL" || colName == "UL" || isNullable) && newValue.Trim().Length == 0)
			{
				return true;
			}
			switch (colName)
			{
			case "LL":
			case "Value":
			case "UL":
				switch ((int)dType)
				{
				case 1:
					double.Parse(newValue, CultureInfo.InvariantCulture);
					break;
				case 0:
					if (newValue.ToUpper().StartsWith("0X"))
					{
						string text = newValue.Remove(0, 2);
						if (text.Length > 0)
						{
							int.Parse(text, NumberStyles.HexNumber);
						}
					}
					else
					{
						int.Parse(newValue);
					}
					break;
				case 6:
					int.Parse(newValue, NumberStyles.HexNumber);
					break;
				case 3:
					short.Parse(newValue);
					break;
				case 4:
					byte.Parse(newValue);
					break;
				case 7:
					uint.Parse(newValue);
					break;
				case 8:
					ushort.Parse(newValue);
					break;
				case 9:
					ulong.Parse(newValue);
					break;
				case 10:
					short.Parse(newValue);
					break;
				case 11:
					long.Parse(newValue);
					break;
				case 13:
					decimal.Parse(newValue);
					break;
				case 15:
					float.Parse(newValue);
					break;
				case 14:
					sbyte.Parse(newValue);
					break;
				case 12:
					char.Parse(newValue.Trim());
					break;
				case 2:
				case 5:
					break;
				}
				break;
			}
		}
		catch (FormatException ex)
		{
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "ValidateParameter " + ex.Message, TraceMessageType.Exception);
			return false;
		}
		catch (Exception ex2)
		{
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "ValidateParameter " + ex2.Message, TraceMessageType.Exception);
			return false;
		}
		return true;
	}

	private void InformTreeViewWithChanges(ParameterCls tParam, string cause)
	{
		RegistrationChanged(cause);
		if (this.OnParameterChanged != null)
		{
			this.OnParameterChanged(this, new ParameterChangeEventArgs(tParam, ParameterState.DontCare, cause, updateChangesToAllParams: true));
		}
		List<string> value = null;
		if (modifiedParams.TryGetValue(tParam.Name, out value))
		{
			if (!value.Contains(cause))
			{
				value.Add(cause);
			}
		}
		else
		{
			value = new List<string>();
			value.Add(cause);
			modifiedParams.Add(tParam.Name, value);
		}
	}

	private void DataLoggingChanged(object sender, CheckState checkState)
	{
		if (this.OnDataLoggingChanged != null)
		{
			this.OnDataLoggingChanged(sender, checkState);
		}
	}

	private void RegistrationChanged(string cause)
	{
		if (this.OnRegistrationChanged != null)
		{
			this.OnRegistrationChanged(this, cause);
		}
	}

	private void paramTableOutput_ColumnChanging(object sender, DataColumnChangeEventArgs e)
	{
		ParameterCls parameterCls = e.Row["Parameter_Object"] as ParameterCls;
		if (e.Column.ColumnName == "LL")
		{
			string text = e.ProposedValue.ToString();
			if (text.Trim() != parameterCls.LowerLimit.Trim())
			{
				if (parameterCls.DataType == DataType.Hex)
				{
					parameterCls.LowerLimit = int.Parse(text, NumberStyles.HexNumber).ToString();
				}
				else
				{
					parameterCls.LowerLimit = text;
				}
				InformTreeViewWithChanges(parameterCls, "LL");
			}
		}
		else if (e.Column.ColumnName == "UL")
		{
			string text2 = e.ProposedValue.ToString();
			if (text2.Trim() != parameterCls.UpperLimit.Trim())
			{
				if (parameterCls.DataType == DataType.Hex)
				{
					parameterCls.UpperLimit = int.Parse(text2, NumberStyles.HexNumber).ToString();
				}
				else
				{
					parameterCls.UpperLimit = text2;
				}
				InformTreeViewWithChanges(parameterCls, "UL");
			}
		}
		else if (e.Column.ColumnName == "Data_Logging")
		{
			if (e.ProposedValue != null)
			{
				if (e.ProposedValue.ToString() == bool.TrueString)
				{
					DataLoggingChanged(this, CheckState.Checked);
					InformTreeViewWithChanges(parameterCls, "Data_Logging_Enabled");
					parameterCls.bEnableDataLogging = true;
				}
				else if (e.ProposedValue.ToString() == bool.FalseString)
				{
					DataLoggingChanged(this, CheckState.Unchecked);
					InformTreeViewWithChanges(parameterCls, "Data_Logging_Disabled");
					parameterCls.bEnableDataLogging = false;
				}
			}
		}
		else if (e.Column.ColumnName == "Reporting_Enabled")
		{
			if (e.ProposedValue == null)
			{
				return;
			}
			if (e.ProposedValue.ToString() == bool.TrueString)
			{
				if (parameterCls.chkEnableCharting != CheckState.Checked)
				{
					InformTreeViewWithChanges(parameterCls, "Reporting_Enabled");
				}
				parameterCls.bEnableCharting = true;
			}
			else if (e.ProposedValue.ToString() == bool.FalseString)
			{
				if (parameterCls.chkEnableCharting != 0)
				{
					InformTreeViewWithChanges(parameterCls, "Charting_Disabled");
				}
				parameterCls.bEnableCharting = false;
			}
		}
		else if (e.Column.ColumnName == "Description")
		{
			string text3 = e.ProposedValue.ToString();
			if (text3.Trim() != parameterCls.Description.Trim())
			{
				parameterCls.Description = text3;
				InformTreeViewWithChanges(parameterCls, "Description");
			}
		}
		else if (e.Column.ColumnName == "Unit")
		{
			string text4 = e.ProposedValue.ToString();
			if (text4.Trim() != parameterCls.Unit.Trim())
			{
				parameterCls.Unit = text4;
				InformTreeViewWithChanges(parameterCls, "Unit");
			}
		}
		else if (e.Column.ColumnName == "GV_Get")
		{
			string text5 = e.ProposedValue.ToString();
			if (text5.Trim() != parameterCls.GlobalVariableName.Trim())
			{
				parameterCls.GlobalVariableName = text5;
				InformTreeViewWithChanges(parameterCls, "GV_Get");
				e.Row["HasGvGetValue"] = !string.IsNullOrWhiteSpace(e.ProposedValue.ToString());
			}
		}
		else if (e.Column.ColumnName == "GV_Set")
		{
			string text6 = e.ProposedValue.ToString();
			if (text6.Trim() != parameterCls.GlobalVariableNameOther.Trim())
			{
				parameterCls.GlobalVariableNameOther = text6;
				InformTreeViewWithChanges(parameterCls, "GV_Set");
			}
		}
		else if (e.Column.ColumnName == "GV_LL_Get")
		{
			string globalVariableForLL = e.ProposedValue.ToString();
			parameterCls.GlobalVariableForLL = globalVariableForLL;
			InformTreeViewWithChanges(parameterCls, "GV_LL_Get");
			e.Row["HasGvGetLL"] = !string.IsNullOrWhiteSpace(e.ProposedValue.ToString());
		}
		else if (e.Column.ColumnName == "GV_UL_Get")
		{
			string text7 = e.ProposedValue.ToString();
			if (text7.Trim() != parameterCls.GlobalVariableForUL.Trim())
			{
				parameterCls.GlobalVariableForUL = text7;
				InformTreeViewWithChanges(parameterCls, "GV_UL_Get");
				e.Row["HasGvGetUL"] = !string.IsNullOrWhiteSpace(e.ProposedValue.ToString());
			}
		}
	}

	private void ResetDataSources()
	{
		childInputDataGridList.Clear();
		childOutputDataGridList.Clear();
		if (refreshInputParam)
		{
			while (paramDataSetInput.Relations.Count > 0)
			{
				paramDataSetInput.Relations.Remove(paramDataSetInput.Relations[0]);
			}
			foreach (DataTable table in paramDataSetInput.Tables)
			{
				paramDataSetInput.Tables[table.TableName].Clear();
			}
			paramDataSetInput.Tables.Clear();
			paramDataSetInput = new DataSet();
			paramTableInput.Clear();
			inputParamRelations.Clear();
		}
		while (paramDataSetOutput.Relations.Count > 0)
		{
			paramDataSetOutput.Relations.Remove(paramDataSetOutput.Relations[0]);
		}
		foreach (DataTable table2 in paramDataSetOutput.Tables)
		{
			paramDataSetOutput.Tables[table2.TableName].Clear();
		}
		paramDataSetOutput.Tables.Clear();
		paramDataSetOutput = new DataSet();
		paramTableOutput.Clear();
		outputParamRelations.Clear();
	}

	private void CreateInputDataRow(ParameterCls pc, DataRow row)
	{
		row["Parameter_Name"] = pc.Name;
		pc.Value = FixBadEnumValues(pc);
		row["Value"] = GetDisplayValue(pc);
		if (pc.DataType == DataType.Hex)
		{
			row["Value"] = int.Parse(pc.Value).ToString("X");
		}
		if (pc.chkEnableDataLogging == CheckState.Checked)
		{
			row["Data_Logging"] = true;
		}
		else if (pc.chkEnableDataLogging == CheckState.Unchecked)
		{
			row["Data_Logging"] = false;
		}
		row["Unit"] = pc.Unit;
		row["Description"] = pc.Description;
		row["GV_Get"] = pc.GlobalVariableName;
		row["GV_Set"] = pc.GlobalVariableNameOther;
		row["Row_ID"] = inputParamRelations.Count - 1;
		row["Parameter_Object"] = pc;
		row["HasChildren"] = false;
		row["HasDifferentValues"] = false;
		row["DifferentValues"] = "";
		row["HasGvGetValue"] = !string.IsNullOrWhiteSpace(pc.GlobalVariableName);
		bool flag = !pc.IsEditableInTestPlan && (ReadOnly || (isFolder && linkParams.Count > 0 && linkParams.Contains(pc.Name)));
		row["IsParamReadOnly"] = flag;
		row["IsParamEditable"] = !flag;
	}

	private string FixBadEnumValues(ParameterCls pc)
	{
		if ((pc.DisplayHint & 8) == 8)
		{
			int result = 0;
			if (pc.Value != null && !int.TryParse(pc.Value, out result))
			{
				if (pc.Value.Contains(' '))
				{
					pc.Value = pc.Value.Substring(0, pc.Value.IndexOf(' '));
				}
				else if (!string.IsNullOrWhiteSpace(pc.Constraints))
				{
					string[] array = pc.Constraints.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
					new List<string>();
					new List<string>();
					for (int i = 0; i < array.Length; i++)
					{
						string text = array[i];
						if (text.Contains('='))
						{
							string[] array2 = text.Split(new char[1] { '=' }, StringSplitOptions.RemoveEmptyEntries);
							if (pc.Value == array2[0])
							{
								pc.Value = array2[1];
							}
						}
						else if (pc.Value == text)
						{
							pc.Value = i.ToString();
						}
					}
				}
			}
		}
		return pc.Value;
	}

	private void CreateOutputDataRow(ParameterCls pc, DataRow row)
	{
		row["Parameter_Name"] = pc.Name;
		if (pc.DataType == DataType.Hex)
		{
			row["LL"] = int.Parse(pc.LowerLimit).ToString("X");
			row["Value"] = int.Parse(pc.Value).ToString("X");
			row["UL"] = int.Parse(pc.UpperLimit).ToString("X");
		}
		else
		{
			row["LL"] = pc.LowerLimit;
			row["Value"] = pc.Value;
			row["UL"] = pc.UpperLimit;
		}
		if (pc.chkEnableDataLogging == CheckState.Checked)
		{
			row["Data_Logging"] = true;
		}
		else if (pc.chkEnableDataLogging == CheckState.Unchecked)
		{
			row["Data_Logging"] = false;
		}
		if (pc.chkEnableCharting == CheckState.Checked)
		{
			row["Reporting_Enabled"] = true;
		}
		else if (pc.chkEnableCharting == CheckState.Unchecked)
		{
			row["Reporting_Enabled"] = false;
		}
		if (pc.chkEnableDataLogging == CheckState.Unchecked)
		{
			row["Logging_Condition"] = "";
		}
		else if (pc.DataLoggingCondition != null && pc.DataLoggingCondition.Enabled)
		{
			row["Logging_Condition"] = "Active";
		}
		else
		{
			row["Logging_Condition"] = "None";
		}
		row["Unit"] = pc.Unit;
		row["Description"] = pc.Description;
		row["GV_Set"] = pc.GlobalVariableNameOther;
		row["GV_Get"] = pc.GlobalVariableName;
		row["GV_LL_Get"] = pc.GlobalVariableForLL;
		row["GV_UL_Get"] = pc.GlobalVariableForUL;
		row["Row_ID"] = outputParamRelations.Count - 1;
		row["Parameter_Object"] = pc;
		row["HasChildren"] = false;
		row["HasDifferentValues"] = false;
		row["DifferentValues"] = "";
		row["HasGvGetLL"] = !string.IsNullOrWhiteSpace(pc.GlobalVariableForLL);
		row["HasGvGetUL"] = !string.IsNullOrWhiteSpace(pc.GlobalVariableForUL);
		bool flag = !pc.IsEditableInTestPlan && (ReadOnly || (isFolder && linkParams.Count > 0 && linkParams.Contains(pc.Name)));
		row["IsParamReadOnly"] = flag;
		row["IsParamEditable"] = !flag;
	}

	public string GetDisplayValue(ParameterCls pc)
	{
		string result = pc.Value;
		try
		{
			if (pc.NoOfElements > 1)
			{
				result = GetArrayDisplayValue(pc);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "GetDisplayValue " + pc.Name + " " + ex.Message, TraceMessageType.Exception);
			return pc.Value;
		}
		return result;
	}

	public string GetArrayDisplayValue(ParameterCls pc)
	{
		if (pc.DisplayHint == 0 || pc.DisplayHint == 256)
		{
			return pc.Value;
		}
		string text = "";
		pc.Constraints.Trim().Split(';');
		string[] array = pc.Value.Trim().Split(',');
		for (int i = 0; i < array.Length; i++)
		{
			try
			{
				text = ((i != 0) ? (text + "," + pc.GetDisplayValue(array[i].Trim())) : pc.GetDisplayValue(array[i].Trim()));
			}
			catch (Exception ex)
			{
				TraceMessage.Write("QC.QTMApplication.TTDParamView", "GetArrayDisplayValue " + ex.Message, TraceMessageType.Exception);
			}
		}
		return text;
	}

	public void ClearParameterDescriptionBox()
	{
		if (this.InvokeRequired())
		{
			this.BeginInvoke(delegate
			{
				ClearParameterDescriptionBox();
			});
		}
		else
		{
			textBoxParamName.Text = "";
			textBoxParamDescrip.Text = "";
		}
	}

	protected virtual void OnPropertyChanged(string propertyName)
	{
		PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
		if (propertyChanged != null)
		{
			PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
			propertyChanged(this, e);
		}
	}

	private void InputDataGrid_GotFocus(object sender, RoutedEventArgs e)
	{
		ExtractParamDescriptionFromSelectedRow(sender as System.Windows.Controls.DataGrid, e);
		e.Handled = true;
	}

	private void ExtractParamDescriptionFromSelectedRow(System.Windows.Controls.DataGrid ultraGrid, RoutedEventArgs e)
	{
		if (ultraGrid.SelectedCells.Count <= 0 && e.OriginalSource is System.Windows.Controls.DataGridCell)
		{
			(e.OriginalSource as System.Windows.Controls.DataGridCell).IsSelected = true;
		}
		if (ultraGrid.SelectedCells.Count <= 0)
		{
			return;
		}
		DataRowView dataRowView = ultraGrid.CurrentCell.Item as DataRowView;
		string parameterName = string.Empty;
		string description = string.Empty;
		if (dataRowView != null)
		{
			if (!Convert.IsDBNull(dataRowView.Row["Parameter_Name"]))
			{
				parameterName = dataRowView.Row["Parameter_Name"].ToString();
			}
			if (!Convert.IsDBNull(dataRowView.Row["Description"].ToString()))
			{
				description = dataRowView.Row["Description"].ToString();
			}
			SetParamDescription(parameterName, description);
		}
	}

	private void SetParamDescription(string parameterName, string description)
	{
		textBoxParamName.Text = parameterName;
		textBoxParamDescrip.Text = description;
	}

	private void OutputDataGrid_GotFocus(object sender, RoutedEventArgs e)
	{
		ExtractParamDescriptionFromSelectedRow(sender as System.Windows.Controls.DataGrid, e);
		e.Handled = true;
	}

	private void GVSetEditCellTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		HandleGVEditClick(sender, e, "GV_Set");
	}

	private void HandleGVEditClick(object sender, RoutedEventArgs e, string columnName)
	{
		e.Handled = true;
		System.Windows.Controls.Control control = sender as System.Windows.Controls.Control;
		DataRowView rowView = control.Tag as DataRowView;
		SelectGlobalVariable(rowView, columnName);
	}

	private void SelectGlobalVariable(DataRowView rowView, string columnTitle)
	{
		QTMGlobalVariablesDialog qTMGlobalVariablesDialog = new QTMGlobalVariablesDialog();
		try
		{
			if (!Convert.IsDBNull(rowView.Row["Parameter_Name"]))
			{
				qTMGlobalVariablesDialog.AssociatedObjectName = rowView.Row["Parameter_Name"].ToString();
			}
			if (!Convert.IsDBNull(rowView.Row[columnTitle]))
			{
				qTMGlobalVariablesDialog.CurrentSelection = rowView.Row[columnTitle].ToString();
			}
			if (qTMGlobalVariablesDialog.ShowDialog(WpfToWin32Window.GetCurrentWin32Window()) == DialogResult.OK)
			{
				rowView.Row[columnTitle] = qTMGlobalVariablesDialog.CurrentSelection;
			}
		}
		catch
		{
		}
	}

	private void GVGetEditCellTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		HandleGVEditClick(sender, e, "GV_Get");
	}

	private void GVGet_UL_EditCellTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		HandleGVEditClick(sender, e, "GV_UL_Get");
	}

	private void GVGet_LL_EditCellTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		HandleGVEditClick(sender, e, "GV_LL_Get");
	}

	private void DataLoggingConditionEditCellTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		System.Windows.Controls.Control control = sender as System.Windows.Controls.Control;
		DataRowView dataRowView = control.Tag as DataRowView;
		if (Convert.IsDBNull(dataRowView.Row["Parameter_Object"]) || !(dataRowView.Row["Parameter_Object"] is ParameterCls parameterCls))
		{
			return;
		}
		PreConditionDialog preConditionDialog = new PreConditionDialog(Test);
		preConditionDialog.DialogType = PreConditionDialog.PreConditionDialogType.LoggingCondition;
		if (parameterCls.DataLoggingCondition != null)
		{
			preConditionDialog.PreConditionMgr = parameterCls.DataLoggingCondition;
		}
		if (preConditionDialog.ShowDialog(WpfToWin32Window.GetCurrentWin32Window()) == DialogResult.OK)
		{
			ParameterCls parameter = GetParameter(parameterCls.Name);
			parameter.DataLoggingCondition = preConditionDialog.PreConditionMgr;
			if (parameter.DataLoggingCondition.Enabled)
			{
				dataRowView.Row["Logging_Condition"] = "Active";
			}
			else
			{
				dataRowView.Row["Logging_Condition"] = "None";
			}
		}
	}

	public ParameterCls GetParameter(string parameterName)
	{
		try
		{
			foreach (ParameterCls parameter in parameters)
			{
				if (parameter.Name == parameterName)
				{
					return parameter;
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.TTDParamView", "GetParameter " + ex.Message, TraceMessageType.Exception);
		}
		return null;
	}

	private void ParameterArrayCellEditTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		e.Handled = true;
		System.Windows.Controls.Control control = sender as System.Windows.Controls.Control;
		DataRowView dataRowView = control.Tag as DataRowView;
		TTDArrayParamEdit tTDArrayParamEdit = new TTDArrayParamEdit();
		dataRowView.Row["Parameter_Name"].ToString();
		ParameterCls parameterCls2 = (tTDArrayParamEdit.Parameter = (ParameterCls)dataRowView.Row["Parameter_Object"]);
		tTDArrayParamEdit.ReadOnly = controlsDisabled || (ReadOnly && !parameterCls2.IsEditableInTestPlan);
		tTDArrayParamEdit.TestType = testType;
		tTDArrayParamEdit.IsArray = ParameterCls.GetIsArray(parameterCls2, IsDotNetTest(), realName, testContainerName);
		if (tTDArrayParamEdit.ShowDialog(WpfToWin32Window.GetCurrentWin32Window()) != DialogResult.OK || controlsDisabled || (ReadOnly && !parameterCls2.IsEditableInTestPlan))
		{
			return;
		}
		UpdateArrayDataLogging(parameterCls2, tTDArrayParamEdit.EnableDataLogging);
		if (parameterCls2.chkEnableDataLogging == CheckState.Checked)
		{
			dataRowView.Row["Data_Logging"] = true;
		}
		else if (parameterCls2.chkEnableDataLogging == CheckState.Unchecked)
		{
			dataRowView.Row["Data_Logging"] = false;
		}
		else
		{
			dataRowView.Row["Data_Logging"] = null;
		}
		if (parameterCls2.Type == IOType.Input)
		{
			arrayEditedWithUI = true;
			dataRowView.Row["Value"] = tTDArrayParamEdit.StringValue;
			arrayEditedWithUI = false;
			if (dataRowView.Row["Value"].ToString().Trim() == parameterCls2.Value.Trim() && parameterCls2.DisplayHint != 0)
			{
				updatingTextValues = true;
				dataRowView.Row["Value"] = GetDisplayValue(parameterCls2);
				updatingTextValues = false;
			}
		}
		else
		{
			parameterCls2.EnableCharting = (ArrayList)tTDArrayParamEdit.EnableCharting.Clone();
			if (parameterCls2.chkEnableCharting == CheckState.Checked)
			{
				dataRowView.Row["Reporting_Enabled"] = true;
			}
			else if (parameterCls2.chkEnableCharting == CheckState.Unchecked)
			{
				dataRowView.Row["Reporting_Enabled"] = false;
			}
			else
			{
				dataRowView.Row["Reporting_Enabled"] = null;
			}
			dataRowView.Row["LL"] = tTDArrayParamEdit.StringLL.Trim();
			dataRowView.Row["UL"] = tTDArrayParamEdit.StringUL.Trim();
		}
	}

	private void UpdateArrayDataLogging(ParameterCls parameter, ArrayList dList)
	{
		try
		{
			bool flag = false;
			try
			{
				for (int i = 0; i < parameter.NoOfElements; i++)
				{
					if (parameter.EnableDataLogging[i].ToString() != dList[i].ToString())
					{
						flag = true;
						break;
					}
				}
			}
			catch (Exception ex)
			{
				flag = true;
				TraceMessage.Write(ToString(), "UpdateArrayDataLogging 1 : " + ex.Message, TraceMessageType.Exception);
			}
			if (flag)
			{
				parameter.EnableDataLogging = (ArrayList)dList.Clone();
				this.OnDataLoggingChanged(this, parameter.chkEnableDataLogging);
			}
		}
		catch (Exception ex2)
		{
			TraceMessage.Write(ToString(), "UpdateArrayDataLogging 2: " + ex2.Message, TraceMessageType.Exception);
		}
	}

	private bool IsDotNetTest()
	{
		if (testType != null)
		{
			return testType.EndsWith("DotNetTest");
		}
		return false;
	}

	private void ParameterDataTableCellEditTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		e.Handled = true;
		System.Windows.Controls.Control control = sender as System.Windows.Controls.Control;
		DataRowView dataRowView = control.Tag as DataRowView;
		ParameterCls parameterCls = dataRowView.Row["Parameter_Object"] as ParameterCls;
		TTDDataTableParamEdit tTDDataTableParamEdit = new TTDDataTableParamEdit();
		tTDDataTableParamEdit.ParamDataTable = parameterCls.DataTableValue;
		tTDDataTableParamEdit.ShowDialog(WpfToWin32Window.GetCurrentWin32Window());
		parameterCls.DataTableValue = tTDDataTableParamEdit.ParamDataTable;
	}

	private void FileValueEditCellTemplateButton_Click(object sender, RoutedEventArgs e)
	{
		e.Handled = true;
		System.Windows.Controls.Control control = sender as System.Windows.Controls.Control;
		DataRowView dataRowView = control.Tag as DataRowView;
		ParameterCls parameterCls = dataRowView.Row["Parameter_Object"] as ParameterCls;
		OpenFileDialog openFileDialog = new OpenFileDialog();
		openFileDialog.RestoreDirectory = true;
		if (Directory.Exists(parameterCls.Constraints.Trim()))
		{
			openFileDialog.InitialDirectory = parameterCls.Constraints.Trim();
		}
		if (openFileDialog.ShowDialog(WpfToWin32Window.GetCurrentWin32Window()) == DialogResult.OK)
		{
			if ((parameterCls.DisplayHint & 4) == 4)
			{
				dataRowView.Row["Value"] = Path.GetFileName(openFileDialog.FileName);
			}
			else
			{
				dataRowView.Row["Value"] = openFileDialog.FileName;
			}
		}
	}

	private void ultraGridInput_LoadingRow(object sender, DataGridRowEventArgs e)
	{
		if (showToolTips && e.Row.Item is DataRowView dataRowView && dataRowView["Parameter_Object"] is ParameterCls tParam)
		{
			object value = CreateToolTipContent(tParam);
			ToolTipService.SetToolTip(e.Row, value);
		}
	}

	private static object CreateToolTipContent(ParameterCls tParam, bool isOutputParam = false)
	{
		StackPanel stackPanel = new StackPanel();
		stackPanel.Orientation = System.Windows.Controls.Orientation.Vertical;
		TextBlock textBlock = new TextBlock();
		textBlock.Text = "Parameter Name: " + tParam.Name;
		stackPanel.Children.Add(textBlock);
		TextBlock textBlock2 = new TextBlock();
		textBlock2.Text = "No of Elements: " + tParam.NoOfElements;
		stackPanel.Children.Add(textBlock2);
		TextBlock textBlock3 = new TextBlock();
		textBlock3.Text = "DataType: " + (tParam.IsNullable ? "Nullable_" : "") + tParam.DataType;
		stackPanel.Children.Add(textBlock3);
		if (isOutputParam && tParam.UseRunTimeLimits)
		{
			TextBlock textBlock4 = new TextBlock();
			textBlock4.Text = "Using Runtime Limits";
			stackPanel.Children.Add(textBlock4);
		}
		return stackPanel;
	}

	private void ultraGridOutput_LoadingRow(object sender, DataGridRowEventArgs e)
	{
		if (showToolTips && e.Row.Item is DataRowView dataRowView && dataRowView["Parameter_Object"] is ParameterCls tParam)
		{
			object value = CreateToolTipContent(tParam, isOutputParam: true);
			ToolTipService.SetToolTip(e.Row, value);
		}
	}

	private void Copy_ParameterName_Click(object sender, RoutedEventArgs e)
	{
		try
		{
			DataRowView dataRowViewFromControlTag = GetDataRowViewFromControlTag(sender);
			if (dataRowViewFromControlTag != null && dataRowViewFromControlTag["Parameter_Object"] is ParameterCls parameterCls)
			{
				System.Windows.Clipboard.SetText(parameterCls.Name);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "mnuCopy_Click " + ex.Message, TraceMessageType.Exception);
		}
	}

	private DataRowView GetDataRowViewFromControlTag(object sender)
	{
		if (sender is System.Windows.Controls.Control control)
		{
			return control.Tag as DataRowView;
		}
		return null;
	}

	private void ExclueParameterLoggingGlobally_Click(object sender, RoutedEventArgs e)
	{
		try
		{
			DataRowView dataRowViewFromControlTag = GetDataRowViewFromControlTag(sender);
			if (dataRowViewFromControlTag != null && dataRowViewFromControlTag["Parameter_Object"] is ParameterCls parameter)
			{
				dataRowViewFromControlTag["Data_Logging"] = false;
				this.OnParameterChanged(this, new ParameterChangeEventArgs(parameter, ParameterState.ExcludeGlobally, "Data_Logging", updateChangesToAllParams: true));
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "mnuExcludeParameter_Click " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void InlcudeParameterLoggingGlobally_Click(object sender, RoutedEventArgs e)
	{
		try
		{
			DataRowView dataRowViewFromControlTag = GetDataRowViewFromControlTag(sender);
			if (dataRowViewFromControlTag != null && dataRowViewFromControlTag["Parameter_Object"] is ParameterCls parameter)
			{
				dataRowViewFromControlTag["Data_Logging"] = true;
				this.OnParameterChanged(this, new ParameterChangeEventArgs(parameter, ParameterState.IncludeGlobally, "Data_Logging", updateChangesToAllParams: true));
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "mnuIncludeParameterGlobally_Click " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void InputGrid_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
	{
		DataTemplate detailsTemplate = FindResource("InputGrid") as DataTemplate;
		e.Row.DetailsTemplate = detailsTemplate;
	}

	private void OutputGrid_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
	{
		DataTemplate detailsTemplate = FindResource("OutputGrid") as DataTemplate;
		e.Row.DetailsTemplate = detailsTemplate;
	}

	private void InputGrid_Loaded(object sender, RoutedEventArgs e)
	{
		bool isChild = false;
		System.Windows.Controls.DataGrid dataGrid = BindChildDataTableToDataSource(sender, paramDataSetInput, isInputParameter: true, out isChild);
		if (isChild)
		{
			NestedDataGridInfo nestedDataGridInfo = new NestedDataGridInfo();
			nestedDataGridInfo.Grid = dataGrid;
			int level = 0;
			System.Windows.Controls.DataGrid parentAndNestedLevel = GetParentAndNestedLevel(dataGrid, mainInputDataGrid, out level);
			nestedDataGridInfo.ParentGrid = parentAndNestedLevel;
			nestedDataGridInfo.Level = level;
			childInputDataGridList.Add(nestedDataGridInfo);
			SyncColumnWidthForChildGrids(childInputDataGridList, mainInputDataGrid);
		}
		else if (uiSettings.MainInputDataGridSettings != null && uiSettings.MainInputDataGridSettings.ColumnSettings.Count > 0)
		{
			uiSettings.MainInputDataGridSettings.LoadGridSettings(mainInputDataGrid);
		}
	}

	private System.Windows.Controls.DataGrid GetParentAndNestedLevel(System.Windows.Controls.DataGrid nestedGrid, System.Windows.Controls.DataGrid rootGrid, out int level)
	{
		level = 0;
		System.Windows.Controls.DataGrid dataGrid = FindParent<System.Windows.Controls.DataGrid>(nestedGrid);
		if (dataGrid != null)
		{
			level++;
			System.Windows.Controls.DataGrid dataGrid2 = dataGrid;
			while (dataGrid2 != rootGrid && dataGrid2 != null)
			{
				dataGrid2 = FindParent<System.Windows.Controls.DataGrid>(dataGrid2);
				level++;
			}
		}
		return dataGrid;
	}

	private System.Windows.Controls.DataGrid BindChildDataTableToDataSource(object sender, DataSet ds, bool isInputParameter, out bool isChild)
	{
		isChild = false;
		System.Windows.Controls.DataGrid dataGrid = sender as System.Windows.Controls.DataGrid;
		DataGridRow dataGridRow = FindParent<DataGridRow>(dataGrid);
		if (dataGridRow != null)
		{
			if (dataGridRow.Item is DataRowView dataRowView)
			{
				string name = dataRowView["Parameter_Name"].ToString();
				if (ds.Tables.Contains(name))
				{
					if (isInputParameter)
					{
						ds.Tables[name].ColumnChanging += paramTableInput_ColumnChanging;
					}
					else
					{
						ds.Tables[name].ColumnChanging += paramTableOutput_ColumnChanging;
					}
					dataGrid.ItemsSource = ds.Tables[name].DefaultView;
					dataGrid.Items.Refresh();
					dataGrid.HeadersVisibility = DataGridHeadersVisibility.None;
					dataGrid.Margin = new Thickness(10.0, 0.0, 0.0, 0.0);
				}
			}
			isChild = true;
		}
		return dataGrid;
	}

	private static T FindParent<T>(DependencyObject depObject) where T : DependencyObject
	{
		DependencyObject parent = VisualTreeHelper.GetParent(depObject);
		if (parent is T)
		{
			return parent as T;
		}
		if (parent == null)
		{
			return null;
		}
		return FindParent<T>(parent);
	}

	private void OutputGrid_Loaded(object sender, RoutedEventArgs e)
	{
		bool isChild = false;
		System.Windows.Controls.DataGrid dataGrid = BindChildDataTableToDataSource(sender, paramDataSetOutput, isInputParameter: false, out isChild);
		if (isChild)
		{
			NestedDataGridInfo nestedDataGridInfo = new NestedDataGridInfo();
			nestedDataGridInfo.Grid = dataGrid;
			int level = 0;
			System.Windows.Controls.DataGrid parentAndNestedLevel = GetParentAndNestedLevel(dataGrid, mainOutputDataGrid, out level);
			nestedDataGridInfo.ParentGrid = parentAndNestedLevel;
			nestedDataGridInfo.Level = level;
			childOutputDataGridList.Add(nestedDataGridInfo);
			SyncColumnWidthForChildGrids(childOutputDataGridList, mainOutputDataGrid);
		}
		else if (uiSettings.MainOutputDataGridSettings != null && uiSettings.MainOutputDataGridSettings.ColumnSettings.Count > 0)
		{
			uiSettings.MainOutputDataGridSettings.LoadGridSettings(mainOutputDataGrid);
		}
	}

	private string GetSettingsFilePath()
	{
		return Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(QSPRMainWindow.FeatureConfigInfo.ConfigDirectory, "TTDParameterViewLayout.config"));
	}

	public void SaveLayout()
	{
		QTMUtility.Serialize(GetSettingsFilePath(), uiSettings);
	}

	private void ShowPopupTextBox(object sender)
	{
		if (sender is System.Windows.Controls.TextBox parentTextBox)
		{
			textPopup.SetParentTextBox(parentTextBox);
			textPopup.IsOpen = true;
		}
	}

	private void DescriptionEdit_PreviewMouseUp(object sender, MouseButtonEventArgs e)
	{
		if (!ReadOnly)
		{
			ShowPopupTextBox(sender);
		}
	}

	private void ValueEditCell_PreviewMouseUp(object sender, MouseButtonEventArgs e)
	{
		if (!ReadOnly)
		{
			ShowPopupTextBox(sender);
		}
	}

	private void TriStateCheckBox_Click(object sender, RoutedEventArgs e)
	{
		if (sender is System.Windows.Controls.CheckBox { IsChecked: null } checkBox)
		{
			checkBox.IsChecked = false;
		}
		e.Handled = true;
	}

	private void paramToolbar_Loaded(object sender, RoutedEventArgs e)
	{
		if (sender is System.Windows.Controls.ToolBar toolBar && toolBar.Template.FindName("OverflowGrid", toolBar) is FrameworkElement frameworkElement)
		{
			frameworkElement.Visibility = Visibility.Collapsed;
		}
	}

	private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
	{
		if (e.Key == Key.Tab)
		{
			System.Windows.Controls.TextBox parentTextBox = textPopup.GetParentTextBox();
			System.Windows.Controls.DataGridCell dataGridCell = parentTextBox.FindParent<System.Windows.Controls.DataGridCell>();
			dataGridCell.Focus();
			dataGridCell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
		}
	}
}
