using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using QC.QsprShared.Dialogs;

namespace QC.QsprTestObjects.TestConditions;

public class FormulaBuilderUC : UserControl
{
	private enum TokenType
	{
		OpParen,
		ClsParen,
		Condition,
		AndOrNot,
		Begin,
		End
	}

	private IContainer components;

	private TextBox textBox1;

	private Button btnAnd;

	private Button btnOr;

	private Button btnNot;

	private Button btnParen;

	private DataGridView gridConditions;

	private Button btnCheck;

	private DataGridViewTextBoxColumn colCondition;

	private DataGridViewTextBoxColumn colName;

	private DataGridViewTextBoxColumn colConditionStr;

	public string Expression
	{
		get
		{
			return textBox1.Text.Trim();
		}
		set
		{
			textBox1.Text = value;
		}
	}

	public int NumberOfConditions => gridConditions.Rows.Count;

	public BaseCondition HighlightedCondition
	{
		set
		{
			bool flag = false;
			if (value == null)
			{
				value = new BaseCondition();
			}
			foreach (DataGridViewRow item in (IEnumerable)gridConditions.Rows)
			{
				if (((BaseCondition)item.Cells[0].Value).Equals(value))
				{
					item.Selected = true;
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			foreach (DataGridViewRow item2 in (IEnumerable)gridConditions.Rows)
			{
				item2.Selected = false;
			}
		}
	}

	public BaseCondition SelectedCondition
	{
		get
		{
			BaseCondition result = null;
			try
			{
				result = gridConditions.SelectedRows[0].Cells[0].Value as BaseCondition;
			}
			catch
			{
			}
			return result;
		}
	}

	public FormulaBuilderUC()
	{
		InitializeComponent();
	}

	public bool CheckSyntax(bool showSuccessDialog)
	{
		int num = 0;
		string text = textBox1.Text;
		char[] anyOf = new char[3] { ' ', '(', ')' };
		int num2 = 0;
		TokenType tokenType = TokenType.Begin;
		while (num < textBox1.Text.Length)
		{
			switch (text[num])
			{
			case ' ':
				num++;
				continue;
			case '(':
				if (tokenType == TokenType.OpParen || tokenType == TokenType.AndOrNot || tokenType == TokenType.Begin)
				{
					num2++;
					tokenType = TokenType.OpParen;
					num++;
					continue;
				}
				AppMessageDialog.Show("Open parenthesis must follow '(', AND, OR, or NOT.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
				textBox1.SelectionStart = num;
				textBox1.SelectionLength = 1;
				return false;
			case ')':
				if (num2 <= 0)
				{
					AppMessageDialog.Show("Parenthesis pairing error.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
					textBox1.SelectionStart = num;
					textBox1.SelectionLength = 1;
					return false;
				}
				if (tokenType == TokenType.Condition || tokenType == TokenType.ClsParen)
				{
					num2--;
					tokenType = TokenType.ClsParen;
					num++;
					continue;
				}
				AppMessageDialog.Show("Close parenthesis must follow either ')' or condition name.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
				textBox1.SelectionStart = num;
				textBox1.SelectionLength = 1;
				return false;
			}
			int num3 = text.IndexOfAny(anyOf, num);
			int num4 = num;
			int num5 = 0;
			string text2;
			if (num3 == -1)
			{
				text2 = text.Substring(num);
				num5 = textBox1.Text.Length - num4;
				num = textBox1.Text.Length;
			}
			else
			{
				text2 = text.Substring(num, num3 - num);
				num5 += num3 - num4;
				num += num3 - num;
			}
			if (text2.Equals("AND", StringComparison.OrdinalIgnoreCase) || text2.Equals("OR", StringComparison.OrdinalIgnoreCase))
			{
				if (tokenType == TokenType.ClsParen || tokenType == TokenType.Condition)
				{
					tokenType = TokenType.AndOrNot;
					continue;
				}
				AppMessageDialog.Show("AND/OR must follow either ')' or a condition name.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
				textBox1.SelectionStart = num4;
				textBox1.SelectionLength = num5;
				return false;
			}
			if (text2.Equals("NOT", StringComparison.OrdinalIgnoreCase))
			{
				if (tokenType == TokenType.OpParen || tokenType == TokenType.AndOrNot || tokenType == TokenType.Begin)
				{
					tokenType = TokenType.AndOrNot;
					continue;
				}
				AppMessageDialog.Show("NOT must follow '(', AND, OR, or NOT.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
				textBox1.SelectionStart = num4;
				textBox1.SelectionLength = num5;
				return false;
			}
			bool flag = false;
			foreach (DataGridViewRow item in (IEnumerable)gridConditions.Rows)
			{
				if (((BaseCondition)item.Cells[0].Value).Name.Equals(text2, StringComparison.OrdinalIgnoreCase))
				{
					flag = true;
					break;
				}
			}
			if (flag)
			{
				if (tokenType != 0 && tokenType != TokenType.AndOrNot && tokenType != TokenType.Begin)
				{
					AppMessageDialog.Show("Condition name must follow '(', AND, OR, or NOT.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
					textBox1.SelectionStart = num4;
					textBox1.SelectionLength = num5;
					return false;
				}
				tokenType = TokenType.Condition;
				continue;
			}
			AppMessageDialog.Show("Unrecognized keyword or condition name: " + text2, "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
			textBox1.SelectionStart = num4;
			textBox1.SelectionLength = num5;
			return false;
		}
		switch (tokenType)
		{
		case TokenType.ClsParen:
		case TokenType.Condition:
			if (num2 != 0)
			{
				AppMessageDialog.Show("Parenthesis pairing error.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
				return false;
			}
			if (showSuccessDialog)
			{
				AppMessageDialog.Show("Expression is valid.", "Syntax Check", DialogResult.OK, MessageDialogType.Information);
			}
			return true;
		case TokenType.Begin:
			AppMessageDialog.Show("Please enter an expression.", "Syntax Check", DialogResult.OK, MessageDialogType.UIWarning);
			return false;
		default:
			AppMessageDialog.Show("Expression must end with ')' or a condition name.", "Syntax Check - FAILED", DialogResult.OK, MessageDialogType.Error);
			return false;
		}
	}

	public void AddCondition(BaseCondition cond)
	{
		gridConditions.Rows.Add(cond, cond.Name, cond.ConditionString);
	}

	public void AddCondition(IEnumerable<BaseCondition> conditionList)
	{
		foreach (BaseCondition condition in conditionList)
		{
			gridConditions.Rows.Add(condition, condition.Name, condition.ConditionString);
		}
	}

	public BaseCondition GetCondition(string name)
	{
		foreach (DataGridViewRow item in (IEnumerable)gridConditions.Rows)
		{
			if (((BaseCondition)item.Cells[0].Value).Name.Equals(name, StringComparison.OrdinalIgnoreCase))
			{
				return item.Cells[0].Value as BaseCondition;
			}
		}
		return null;
	}

	public BaseCondition GetCondition(int index)
	{
		try
		{
			return gridConditions.Rows[index].Cells[0].Value as BaseCondition;
		}
		catch
		{
		}
		return null;
	}

	public void RemoveAllConditions()
	{
		while (gridConditions.Rows.Count > 0)
		{
			gridConditions.Rows.Remove(gridConditions.Rows[gridConditions.Rows.Count - 1]);
		}
	}

	public BaseCondition RemoveCondition(string name)
	{
		BaseCondition result = null;
		DataGridViewRow dataGridViewRow = null;
		foreach (DataGridViewRow item in (IEnumerable)gridConditions.Rows)
		{
			try
			{
				if (((BaseCondition)item.Cells[0].Value).Name.Equals(name, StringComparison.OrdinalIgnoreCase))
				{
					result = item.Cells[0].Value as BaseCondition;
					dataGridViewRow = item;
					break;
				}
			}
			catch
			{
			}
		}
		if (dataGridViewRow != null)
		{
			gridConditions.Rows.Remove(dataGridViewRow);
		}
		return result;
	}

	public BaseCondition RemoveCondition(int index)
	{
		BaseCondition result = null;
		try
		{
			result = gridConditions.Rows[index].Cells[0].Value as BaseCondition;
			gridConditions.Rows.Remove(gridConditions.Rows[index]);
		}
		catch
		{
		}
		return result;
	}

	public BaseCondition RemoveCondition(BaseCondition cond)
	{
		BaseCondition result = null;
		DataGridViewRow dataGridViewRow = null;
		foreach (DataGridViewRow item in (IEnumerable)gridConditions.Rows)
		{
			if (((BaseCondition)item.Cells[0].Value).Equals(cond))
			{
				result = item.Cells[0].Value as BaseCondition;
				dataGridViewRow = item;
				break;
			}
		}
		if (dataGridViewRow != null)
		{
			gridConditions.Rows.Remove(dataGridViewRow);
		}
		return result;
	}

	public void AddGridSelectionChangeHandler(EventHandler handler)
	{
		gridConditions.SelectionChanged += handler;
	}

	public void UpdateConditionStrings()
	{
		foreach (DataGridViewRow item in (IEnumerable)gridConditions.Rows)
		{
			item.Cells[1].Value = ((BaseCondition)item.Cells[0].Value).Name;
			item.Cells[2].Value = ((BaseCondition)item.Cells[0].Value).ConditionString;
		}
	}

	private void btnAnd_Click(object sender, EventArgs e)
	{
		InsertWord("AND");
	}

	private void btnOr_Click(object sender, EventArgs e)
	{
		InsertWord("OR");
	}

	private void btnNot_Click(object sender, EventArgs e)
	{
		InsertWord("NOT");
	}

	private void btnParen_Click(object sender, EventArgs e)
	{
		if (textBox1.SelectionLength == 0)
		{
			InsertWord("(  )");
		}
		else
		{
			int selectionStart = textBox1.SelectionStart;
			int num = selectionStart + textBox1.SelectionLength;
			int num2 = 0;
			string text = textBox1.Text;
			textBox1.Text = text.Substring(0, selectionStart) + '(' + text.Substring(selectionStart, num - selectionStart) + ')' + text.Substring(num);
			num += 2;
			num2 = InsertSpaces(selectionStart, num);
			InsertSpaces(selectionStart + num2 + 1, num + num2 - 1);
		}
		textBox1.SelectionStart -= 2;
	}

	private void btnCheck_Click(object sender, EventArgs e)
	{
		CheckSyntax(showSuccessDialog: true);
	}

	private void gridConditions_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
	{
		if (e.RowIndex >= 0)
		{
			InsertWord(((BaseCondition)gridConditions.Rows[e.RowIndex].Cells[0].Value).Name);
		}
	}

	private void InsertWord(string word)
	{
		textBox1.SelectedText = word;
		InsertSpaces(textBox1.SelectionStart - word.Length, textBox1.SelectionStart);
	}

	private int InsertSpaces(int start, int end)
	{
		int result = 0;
		if (start > 0 && textBox1.Text[start - 1] != ' ')
		{
			textBox1.Text = textBox1.Text.Substring(0, start) + ' ' + textBox1.Text.Substring(start);
			end++;
			result = 1;
		}
		if (end < textBox1.Text.Length && textBox1.Text[end] != ' ')
		{
			textBox1.Text = textBox1.Text.Substring(0, end) + ' ' + textBox1.Text.Substring(end);
		}
		textBox1.SelectionStart = end;
		return result;
	}

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

	private void InitializeComponent()
	{
		System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle = new System.Windows.Forms.DataGridViewCellStyle();
		System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
		System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
		this.textBox1 = new System.Windows.Forms.TextBox();
		this.btnAnd = new System.Windows.Forms.Button();
		this.btnOr = new System.Windows.Forms.Button();
		this.btnNot = new System.Windows.Forms.Button();
		this.btnParen = new System.Windows.Forms.Button();
		this.gridConditions = new System.Windows.Forms.DataGridView();
		this.btnCheck = new System.Windows.Forms.Button();
		this.colCondition = new System.Windows.Forms.DataGridViewTextBoxColumn();
		this.colName = new System.Windows.Forms.DataGridViewTextBoxColumn();
		this.colConditionStr = new System.Windows.Forms.DataGridViewTextBoxColumn();
		((System.ComponentModel.ISupportInitialize)this.gridConditions).BeginInit();
		base.SuspendLayout();
		this.textBox1.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.textBox1.BackColor = System.Drawing.SystemColors.Window;
		this.textBox1.HideSelection = false;
		this.textBox1.Location = new System.Drawing.Point(0, 231);
		this.textBox1.Name = "textBox1";
		this.textBox1.Size = new System.Drawing.Size(443, 20);
		this.textBox1.TabIndex = 0;
		this.btnAnd.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnAnd.Location = new System.Drawing.Point(359, 24);
		this.btnAnd.Name = "btnAnd";
		this.btnAnd.Size = new System.Drawing.Size(75, 23);
		this.btnAnd.TabIndex = 2;
		this.btnAnd.Text = "AND";
		this.btnAnd.UseVisualStyleBackColor = true;
		this.btnAnd.Click += new System.EventHandler(btnAnd_Click);
		this.btnOr.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnOr.Location = new System.Drawing.Point(359, 53);
		this.btnOr.Name = "btnOr";
		this.btnOr.Size = new System.Drawing.Size(75, 23);
		this.btnOr.TabIndex = 3;
		this.btnOr.Text = "OR";
		this.btnOr.UseVisualStyleBackColor = true;
		this.btnOr.Click += new System.EventHandler(btnOr_Click);
		this.btnNot.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnNot.Location = new System.Drawing.Point(359, 82);
		this.btnNot.Name = "btnNot";
		this.btnNot.Size = new System.Drawing.Size(75, 23);
		this.btnNot.TabIndex = 4;
		this.btnNot.Text = "NOT";
		this.btnNot.UseVisualStyleBackColor = true;
		this.btnNot.Click += new System.EventHandler(btnNot_Click);
		this.btnParen.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
		this.btnParen.Location = new System.Drawing.Point(359, 111);
		this.btnParen.Name = "btnParen";
		this.btnParen.Size = new System.Drawing.Size(75, 23);
		this.btnParen.TabIndex = 5;
		this.btnParen.Text = "(  )";
		this.btnParen.UseVisualStyleBackColor = true;
		this.btnParen.Click += new System.EventHandler(btnParen_Click);
		this.gridConditions.AllowUserToAddRows = false;
		this.gridConditions.AllowUserToDeleteRows = false;
		this.gridConditions.AllowUserToResizeRows = false;
		this.gridConditions.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.gridConditions.BackgroundColor = System.Drawing.SystemColors.Window;
		this.gridConditions.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
		dataGridViewCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
		dataGridViewCellStyle.BackColor = System.Drawing.SystemColors.Control;
		dataGridViewCellStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
		dataGridViewCellStyle.ForeColor = System.Drawing.SystemColors.WindowText;
		dataGridViewCellStyle.SelectionBackColor = System.Drawing.SystemColors.Highlight;
		dataGridViewCellStyle.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
		dataGridViewCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
		this.gridConditions.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle;
		this.gridConditions.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
		this.gridConditions.Columns.AddRange(this.colCondition, this.colName, this.colConditionStr);
		dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
		dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window;
		dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
		dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText;
		dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
		dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
		dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
		this.gridConditions.DefaultCellStyle = dataGridViewCellStyle2;
		this.gridConditions.GridColor = System.Drawing.SystemColors.Window;
		this.gridConditions.Location = new System.Drawing.Point(0, 0);
		this.gridConditions.MultiSelect = false;
		this.gridConditions.Name = "gridConditions";
		this.gridConditions.ReadOnly = true;
		dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
		dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control;
		dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
		dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText;
		dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
		dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
		dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
		this.gridConditions.RowHeadersDefaultCellStyle = dataGridViewCellStyle3;
		this.gridConditions.RowHeadersVisible = false;
		this.gridConditions.RowHeadersWidth = 18;
		this.gridConditions.RowTemplate.Height = 17;
		this.gridConditions.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
		this.gridConditions.Size = new System.Drawing.Size(347, 225);
		this.gridConditions.StandardTab = true;
		this.gridConditions.TabIndex = 1;
		this.gridConditions.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(gridConditions_CellDoubleClick);
		this.btnCheck.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
		this.btnCheck.Location = new System.Drawing.Point(359, 202);
		this.btnCheck.Name = "btnCheck";
		this.btnCheck.Size = new System.Drawing.Size(84, 23);
		this.btnCheck.TabIndex = 6;
		this.btnCheck.Text = "Check Syntax";
		this.btnCheck.UseVisualStyleBackColor = true;
		this.btnCheck.Click += new System.EventHandler(btnCheck_Click);
		this.colCondition.HeaderText = "ConditionObject";
		this.colCondition.Name = "colCondition";
		this.colCondition.ReadOnly = true;
		this.colCondition.Resizable = System.Windows.Forms.DataGridViewTriState.False;
		this.colCondition.Visible = false;
		this.colName.HeaderText = "Name";
		this.colName.Name = "colName";
		this.colName.ReadOnly = true;
		this.colName.Resizable = System.Windows.Forms.DataGridViewTriState.False;
		this.colConditionStr.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
		this.colConditionStr.HeaderText = "Condition";
		this.colConditionStr.Name = "colConditionStr";
		this.colConditionStr.ReadOnly = true;
		this.colConditionStr.Resizable = System.Windows.Forms.DataGridViewTriState.False;
		base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
		base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
		this.BackColor = System.Drawing.SystemColors.Window;
		base.Controls.Add(this.btnCheck);
		base.Controls.Add(this.gridConditions);
		base.Controls.Add(this.btnParen);
		base.Controls.Add(this.btnNot);
		base.Controls.Add(this.btnOr);
		base.Controls.Add(this.btnAnd);
		base.Controls.Add(this.textBox1);
		base.Name = "FormulaBuilderUC";
		base.Size = new System.Drawing.Size(443, 252);
		((System.ComponentModel.ISupportInitialize)this.gridConditions).EndInit();
		base.ResumeLayout(false);
		base.PerformLayout();
	}
}
