using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using QC.QsprShared.Dialogs;
using QC.QsprShared.Trace;
using QC.QsprTestObjects.Loops;
using QC.QsprTestObjects.Parameters;
using QC.QsprTestObjects.Tests.Base;
using QC.QTMApplication.Utilities;
using QC.QTMInterface;
using QC.QTMSecurity;

namespace QC.QTMApplication;

public class TTDLoopView : UserControl
{
	public delegate void LoopSelectionChangedDelegate(object sender, EventArgs e);

	public delegate void ShowLoopSetupDelegate(object sender, EventArgs e);

	private DataGridView loopGrid;

	private ToolTip toolTip;

	private Label labelLoopWarningMsg;

	private Panel panel1;

	private ToolStrip toolStripLoopView;

	private Panel panel2;

	private ToolStripButton EditLoops;

	private ToolStripButton SelectAll;

	private ToolStripButton DeselectAll;

	private IContainer components;

	private object currentTest;

	private WSpaceConfig wsc = default(WSpaceConfig);

	private bool readOnly;

	private bool bLoading;

	private LoopScenarioValues currScenarios = new LoopScenarioValues();

	private string currTestPath = "";

	public BaseTest CurrentTest
	{
		set
		{
			try
			{
				if (value == null)
				{
					ClearGrid();
					currTestPath = null;
					return;
				}
				if (value.TestPath == currTestPath)
				{
					currTestPath = value.TestPath;
					return;
				}
				ClearGrid();
				currTestPath = value.TestPath;
				labelLoopWarningMsg.Visible = false;
				if (value == null)
				{
					return;
				}
				currentTest = value;
				currScenarios = new LoopScenarioValues();
				if (currentTest is FolderTest)
				{
					currScenarios = ((FolderTest)currentTest).FolderProperties.Scenarios;
				}
				else
				{
					currScenarios = ((BaseTest)currentTest).Properties.Scenarios;
				}
				if (currScenarios == null)
				{
					return;
				}
				try
				{
					bLoading = true;
					LoadGrid();
				}
				catch
				{
				}
				finally
				{
					bLoading = false;
				}
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "CurrentFolder " + ex.Message, TraceMessageType.Exception);
			}
		}
	}

	public bool ReadOnly
	{
		get
		{
			return readOnly;
		}
		set
		{
			readOnly = value;
		}
	}

	public string CurrTestPath
	{
		set
		{
			currTestPath = value;
		}
	}

	public event LoopSelectionChangedDelegate OnLoopSelectionChanged;

	public event ShowLoopSetupDelegate ShowLoopSetupEvent;

	protected override void Dispose(bool disposing)
	{
		if (disposing && components != null)
		{
			components.Dispose();
		}
		base.Dispose(disposing);
	}

	private void InitializeComponent()
	{
		this.components = new System.ComponentModel.Container();
		System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QC.QTMApplication.TTDLoopView));
		this.loopGrid = new System.Windows.Forms.DataGridView();
		this.toolTip = new System.Windows.Forms.ToolTip(this.components);
		this.labelLoopWarningMsg = new System.Windows.Forms.Label();
		this.panel1 = new System.Windows.Forms.Panel();
		this.toolStripLoopView = new System.Windows.Forms.ToolStrip();
		this.EditLoops = new System.Windows.Forms.ToolStripButton();
		this.SelectAll = new System.Windows.Forms.ToolStripButton();
		this.DeselectAll = new System.Windows.Forms.ToolStripButton();
		this.panel2 = new System.Windows.Forms.Panel();
		((System.ComponentModel.ISupportInitialize)this.loopGrid).BeginInit();
		this.panel1.SuspendLayout();
		this.toolStripLoopView.SuspendLayout();
		this.panel2.SuspendLayout();
		base.SuspendLayout();
		this.loopGrid.AllowUserToAddRows = false;
		this.loopGrid.AllowUserToDeleteRows = false;
		this.loopGrid.Cursor = System.Windows.Forms.Cursors.Default;
		this.loopGrid.Dock = System.Windows.Forms.DockStyle.Fill;
		this.loopGrid.Location = new System.Drawing.Point(0, 0);
		this.loopGrid.MultiSelect = false;
		this.loopGrid.Name = "loopGrid";
		this.loopGrid.Size = new System.Drawing.Size(660, 329);
		this.loopGrid.TabIndex = 0;
		this.loopGrid.CellMouseEnter += new System.Windows.Forms.DataGridViewCellEventHandler(loopGrid_MouseEnterElement);
		this.loopGrid.CellMouseLeave += new System.Windows.Forms.DataGridViewCellEventHandler(loopGrid_MouseLeaveElement);
		this.loopGrid.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(loopGrid_ColumnAdded);
		this.loopGrid.CurrentCellDirtyStateChanged += new System.EventHandler(loopGrid_CellChange);
		this.loopGrid.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(loopGrid_InitializeRow);
		this.labelLoopWarningMsg.AutoSize = true;
		this.labelLoopWarningMsg.BackColor = System.Drawing.Color.Transparent;
		this.labelLoopWarningMsg.Location = new System.Drawing.Point(3, 10);
		this.labelLoopWarningMsg.Name = "labelLoopWarningMsg";
		this.labelLoopWarningMsg.Size = new System.Drawing.Size(619, 13);
		this.labelLoopWarningMsg.TabIndex = 5;
		this.labelLoopWarningMsg.Text = "Number of loop conditions has exceeded max number of conditions allowed.  Please go to Loop Setup to change loop conditions. ";
		this.labelLoopWarningMsg.Visible = false;
		this.panel1.Controls.Add(this.toolStripLoopView);
		this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
		this.panel1.Location = new System.Drawing.Point(0, 0);
		this.panel1.Name = "panel1";
		this.panel1.Size = new System.Drawing.Size(660, 27);
		this.panel1.TabIndex = 6;
		this.toolStripLoopView.Dock = System.Windows.Forms.DockStyle.Fill;
		this.toolStripLoopView.Items.AddRange(new System.Windows.Forms.ToolStripItem[3] { this.EditLoops, this.SelectAll, this.DeselectAll });
		this.toolStripLoopView.Location = new System.Drawing.Point(0, 0);
		this.toolStripLoopView.Name = "toolStripLoopView";
		this.toolStripLoopView.Size = new System.Drawing.Size(660, 27);
		this.toolStripLoopView.TabIndex = 0;
		this.toolStripLoopView.Text = "toolStripLoopView";
		this.toolStripLoopView.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(toolStripLoopView_ItemClicked);
		this.EditLoops.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
		this.EditLoops.Image = (System.Drawing.Image)resources.GetObject("EditLoops.Image");
		this.EditLoops.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.EditLoops.Name = "EditLoops";
		this.EditLoops.Size = new System.Drawing.Size(23, 24);
		this.EditLoops.Text = "toolStripButton1";
		this.EditLoops.ToolTipText = "Edit Loop Setup";
		this.SelectAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
		this.SelectAll.Image = (System.Drawing.Image)resources.GetObject("SelectAll.Image");
		this.SelectAll.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.SelectAll.Name = "SelectAll";
		this.SelectAll.Size = new System.Drawing.Size(23, 24);
		this.SelectAll.Text = "toolStripButton2";
		this.SelectAll.ToolTipText = "Check All Rows";
		this.DeselectAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
		this.DeselectAll.Image = (System.Drawing.Image)resources.GetObject("DeselectAll.Image");
		this.DeselectAll.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.DeselectAll.Name = "DeselectAll";
		this.DeselectAll.Size = new System.Drawing.Size(23, 24);
		this.DeselectAll.Text = "toolStripButton3";
		this.DeselectAll.ToolTipText = "Uncheck All Rows";
		this.panel2.Controls.Add(this.labelLoopWarningMsg);
		this.panel2.Controls.Add(this.loopGrid);
		this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
		this.panel2.Location = new System.Drawing.Point(0, 27);
		this.panel2.Name = "panel2";
		this.panel2.Size = new System.Drawing.Size(660, 329);
		this.panel2.TabIndex = 7;
		base.Controls.Add(this.panel2);
		base.Controls.Add(this.panel1);
		base.Name = "TTDLoopView";
		base.Size = new System.Drawing.Size(660, 356);
		((System.ComponentModel.ISupportInitialize)this.loopGrid).EndInit();
		this.panel1.ResumeLayout(false);
		this.panel1.PerformLayout();
		this.toolStripLoopView.ResumeLayout(false);
		this.toolStripLoopView.PerformLayout();
		this.panel2.ResumeLayout(false);
		this.panel2.PerformLayout();
		base.ResumeLayout(false);
	}

	public TTDLoopView()
	{
		InitializeComponent();
		base.GotFocus += TTDLoopView_GotFocus;
		base.LostFocus += TTDLoopView_LostFocus;
	}

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

	private void TTDLoopView_GotFocus(object sender, EventArgs e)
	{
		HelpUtility.CurrentFocusedControl = HelpUtility.FocusedControl.LoopView;
	}

	protected void ClearGrid()
	{
		loopGrid.Rows.Clear();
		loopGrid.Columns.Clear();
	}

	private void LoadGrid()
	{
		try
		{
			loopGrid.Hide();
			loopGrid.Rows.Clear();
			loopGrid.Columns.Clear();
			loopGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
			int num = 1;
			if (LoopSetup.IsExceedMaxLoopCount(currScenarios))
			{
				labelLoopWarningMsg.Visible = true;
				return;
			}
			labelLoopWarningMsg.Visible = false;
			for (num = 1; num <= currScenarios.LoopConditions.Count; num++)
			{
				LoopCondition loopCondition = (LoopCondition)currScenarios.LoopConditions[num - 1];
				AppendColumn(loopCondition, loopCondition.LoopValues);
			}
			CheckGridRows(currScenarios.ConditionCheck);
			AddDescription(currScenarios.Descriptions);
			AddDontRunContition(currScenarios.DontRunCondition);
			loopGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "LoadGrid " + ex.Message, TraceMessageType.Exception);
		}
		loopGrid.Show();
	}

	private void AppendColumn(LoopCondition loop, ArrayList loopValues)
	{
		string loopName = loop.LoopName;
		try
		{
			if (loopGrid.Columns.Count == 0)
			{
				DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
				dataGridViewTextBoxColumn.Name = "Row ID";
				loopGrid.Columns.Add(dataGridViewTextBoxColumn);
				DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn = new DataGridViewCheckBoxColumn();
				dataGridViewCheckBoxColumn.Name = "Selection";
				loopGrid.Columns.Add(dataGridViewCheckBoxColumn);
				DataGridViewTextBoxColumn dataGridViewTextBoxColumn2 = new DataGridViewTextBoxColumn();
				dataGridViewTextBoxColumn2.Name = "Don't Run Condition";
				loopGrid.Columns.Add(dataGridViewTextBoxColumn2);
				DataGridViewTextBoxColumn dataGridViewTextBoxColumn3 = new DataGridViewTextBoxColumn();
				dataGridViewTextBoxColumn3.Name = "Description";
				loopGrid.Columns.Add(dataGridViewTextBoxColumn3);
			}
			DataGridViewTextBoxColumn dataGridViewTextBoxColumn4 = new DataGridViewTextBoxColumn();
			dataGridViewTextBoxColumn4.Name = loopName;
			loopGrid.Columns.Add(dataGridViewTextBoxColumn4);
			if (loopGrid.Rows.Count < loopValues.Count)
			{
				int count = loopGrid.Rows.Count;
				for (int i = 0; i < loopValues.Count - count; i++)
				{
					loopGrid.Rows.Add();
				}
			}
			if (loop.LoopType != QC.QsprTestObjects.Loops.LoopTypes.BYSEQUENCE)
			{
				List<string> displayStrings = loop.GetDisplayStrings((currentTest as BaseTest).Root, loopValues, (currentTest as BaseTest).Index, loop.ParamName, loop.OriginalValue);
				for (int j = 0; j < displayStrings.Count; j++)
				{
					try
					{
						if (displayStrings[j].Trim() != "")
						{
							loopGrid.Rows[j].Cells[loopName].Value = displayStrings[j];
							UpdateCellValue(loopGrid.Rows[j].Cells[loopName]);
						}
					}
					catch (Exception ex)
					{
						TraceMessage.Write(ToString(), "AppendColumn " + ex.Message, TraceMessageType.Exception);
					}
				}
				return;
			}
			for (int k = 0; k < loopValues.Count; k++)
			{
				try
				{
					if (loopValues[k].ToString().Trim() != "")
					{
						loopGrid.Rows[k].Cells[loopName].Value = loop.GetDisplayString((currentTest as BaseTest).Root, loopValues[k].ToString());
						UpdateCellValue(loopGrid.Rows[k].Cells[loopName]);
					}
				}
				catch (Exception ex2)
				{
					TraceMessage.Write(ToString(), "AppendColumn " + ex2.Message, TraceMessageType.Exception);
				}
			}
		}
		catch (Exception ex3)
		{
			AppMessageDialog.Show(ex3.Message, "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, DialogResult.OK, MessageDialogType.Exception);
		}
	}

	private void CheckGridRows(ArrayList list)
	{
		try
		{
			foreach (DataGridViewRow item in (IEnumerable)loopGrid.Rows)
			{
				item.Cells[1].Value = true;
			}
			if (list.Count != loopGrid.Rows.Count)
			{
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				bool flag = true;
				try
				{
					flag = bool.Parse(list[i].ToString());
				}
				catch (FormatException)
				{
				}
				catch (ArgumentNullException)
				{
				}
				if (!flag)
				{
					loopGrid.Rows[i].Cells["Selection"].Value = flag;
				}
			}
		}
		catch (Exception ex3)
		{
			TraceMessage.Write(ToString(), "CheckGridRows " + ex3.Message, TraceMessageType.Exception);
		}
	}

	private void AddDescription(ArrayList list)
	{
		try
		{
			int num = 0;
			foreach (string item in list)
			{
				loopGrid[3, num].Value = item;
				num++;
			}
		}
		catch
		{
		}
	}

	private void AddDontRunContition(ArrayList list)
	{
		try
		{
			int num = 0;
			foreach (string item in list)
			{
				loopGrid[2, num].Value = item;
				num++;
			}
		}
		catch
		{
		}
	}

	private void loopGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
	{
		e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
		foreach (DataGridViewColumn column in loopGrid.Columns)
		{
			switch (column.Index)
			{
			case 0:
				e.Column.ReadOnly = true;
				e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
				e.Column.Width = 50;
				e.Column.MinimumWidth = 50;
				break;
			case 1:
				e.Column.ReadOnly = false;
				e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
				e.Column.Width = 55;
				e.Column.MinimumWidth = 55;
				break;
			default:
				e.Column.ReadOnly = true;
				e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
				break;
			}
		}
	}

	private void loopGrid_InitializeRow(object sender, DataGridViewRowsAddedEventArgs e)
	{
		for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++)
		{
			DataGridViewRow dataGridViewRow = loopGrid.Rows[i];
			dataGridViewRow.Cells[0].Value = i + 1;
			dataGridViewRow.Cells[1].Value = true;
			dataGridViewRow.Cells[2].Value = "";
			dataGridViewRow.Cells[3].Value = "";
		}
	}

	private void loopGrid_CellChange(object sender, EventArgs e)
	{
		if (loopGrid.CurrentCell.OwningColumn.HeaderText == "Selection")
		{
			loopGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
			if (currentTest is FolderTest)
			{
				currScenarios = ((FolderTest)currentTest).FolderProperties.Scenarios;
			}
			else
			{
				currScenarios = ((BaseTest)currentTest).Properties.Scenarios;
			}
			currScenarios.ConditionCheck = GetCheckedRows();
			((BaseTest)currentTest).Root.Scheduler.GlobalStatus.RegistrationStatus.LoopSelectionChanged = true;
		}
	}

	private void loopGrid_MouseEnterElement(object sender, DataGridViewCellEventArgs e)
	{
		try
		{
			if (!wsc.ShowToolTips || e.ColumnIndex == -1 || e.RowIndex == -1)
			{
				return;
			}
			DataGridViewCell dataGridViewCell = loopGrid[e.ColumnIndex, e.RowIndex];
			string headerText = dataGridViewCell.OwningColumn.HeaderText;
			if (headerText == null || !GetLoopCondition(headerText, out var loopCondition))
			{
				return;
			}
			string text = "Loop name: " + loopCondition.LoopName;
			switch (loopCondition.LoopType)
			{
			case QC.QsprTestObjects.Loops.LoopTypes.STARTSTOPSTEP:
				text = text + "\nTest name: " + loopCondition.TestName;
				text = text + "\nParameter name: " + loopCondition.ParamName;
				text = text + "\nStart,Stop,Step: " + loopCondition.OriginalValue;
				break;
			case QC.QsprTestObjects.Loops.LoopTypes.LIST:
				text = text + "\nTest name: " + loopCondition.TestName;
				text = text + "\nParameter name: " + loopCondition.ParamName;
				if (loopCondition.LoopDetails.Trim().Length > 0)
				{
					string[] array = loopCondition.LoopDetails.Split(new string[1] { "@#$%" }, StringSplitOptions.None);
					text = ((string.Compare(array[3], "True") != 0) ? (text + "\nFile Name: " + array[1]) : (text + "\nFile Name\\GV Name: " + array[1]));
					text = text + "\nColumn Name: " + array[2];
					text = text + "\nValue Separator: " + array[0];
				}
				break;
			case QC.QsprTestObjects.Loops.LoopTypes.BYTIME:
				text = text + "\nUnits: " + loopCondition.LoopDetails;
				break;
			}
			toolTip.SetToolTip(loopGrid, text);
			toolTip.Active = true;
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "loopGrid_MouseEnterElement " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void loopGrid_MouseLeaveElement(object sender, DataGridViewCellEventArgs e)
	{
		toolTip.Active = false;
	}

	private void UpdateCellValue(DataGridViewCell currentCell)
	{
		try
		{
			string headerText = currentCell.OwningColumn.HeaderText;
			string currentValue = currentCell.Value.ToString();
			if (GetParamNameIndex(headerText, out var pName, out var testIndex))
			{
				BaseTest baseTest = null;
				baseTest = ((!(currentTest is FolderTest)) ? ((BaseTest)currentTest) : ((FolderTest)currentTest).FindTest(testIndex));
				if (baseTest != null)
				{
					ParameterCls parameter = baseTest.Properties.Parameters.GetParameter(pName);
					currentCell.Value = parameter.GetDisplayValue(currentValue);
				}
			}
		}
		catch
		{
		}
	}

	private bool GetLoopCondition(string lName, out LoopCondition loopCondition)
	{
		loopCondition = new LoopCondition();
		try
		{
			foreach (LoopCondition loopCondition2 in currScenarios.LoopConditions)
			{
				if (loopCondition2.LoopName.Trim() == lName.Trim())
				{
					loopCondition = loopCondition2.Clone();
					return true;
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "GetParamName " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	private bool GetParamNameIndex(string lName, out string pName, out string testIndex)
	{
		pName = "";
		testIndex = "";
		try
		{
			foreach (LoopCondition loopCondition in currScenarios.LoopConditions)
			{
				if (loopCondition.LoopName.Trim() == lName.Trim())
				{
					pName = loopCondition.ParamName;
					testIndex = loopCondition.TestIndex;
					return true;
				}
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "GetParamName " + ex.Message, TraceMessageType.Exception);
		}
		return false;
	}

	public void OnConfigInfo(WSpaceConfig wConf)
	{
		try
		{
			wsc = wConf;
			if (wsc.ShowToolTips)
			{
				loopGrid.ShowCellToolTips = true;
			}
			else
			{
				loopGrid.ShowCellToolTips = false;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnConfigInfo " + ex.Message, TraceMessageType.Exception);
		}
	}

	private ArrayList GetCheckedRows()
	{
		try
		{
			ArrayList arrayList = new ArrayList();
			foreach (DataGridViewRow item in (IEnumerable)loopGrid.Rows)
			{
				if (item.Cells[1].Value.ToString().ToUpper() == "TRUE")
				{
					arrayList.Add(true);
				}
				else
				{
					arrayList.Add(false);
				}
			}
			return arrayList;
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("ERROR: " + ex.Message, "QSPR - TTDLoopView", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Exception);
		}
		return null;
	}

	private void toolStripLoopView_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
	{
		if (QSecurity.LockedQGroup)
		{
			return;
		}
		try
		{
			if (!QSecurity.IsTechnician)
			{
				return;
			}
			switch (e.ClickedItem.Name)
			{
			case "SelectAll":
				loopGrid.CurrentCell = null;
				foreach (DataGridViewRow item in (IEnumerable)loopGrid.Rows)
				{
					item.Cells[1].Value = true;
				}
				loopGrid.Update();
				currScenarios.ConditionCheck = GetCheckedRows();
				break;
			case "DeselectAll":
				loopGrid.CurrentCell = null;
				foreach (DataGridViewRow item2 in (IEnumerable)loopGrid.Rows)
				{
					item2.Cells[1].Value = false;
				}
				loopGrid.Update();
				currScenarios.ConditionCheck = GetCheckedRows();
				break;
			case "EditLoops":
				if (this.ShowLoopSetupEvent != null)
				{
					this.ShowLoopSetupEvent(this, new EventArgs());
				}
				break;
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("ERROR: " + ex.Message, "QSPR - TTDLoopView", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Exception);
		}
	}

	public void EnableControls(bool enable)
	{
		loopGrid.Enabled = enable;
	}
}
