using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using QC.QTMDotNetKernelInterface;
using QC.QTMInterface;
using QC.QTMSecurity;
using QsprMiscShared.Utilities;

namespace GlobalVariableViewWPF;

public partial class GlobalVariableViewWPF : UserControl, IComponentConnector
{
	public delegate void UserPluginMessageEventHandler(object sender, TTDPluginEventArgs e);

	private bool updatingGlobalVariables;

	private Dictionary<string, GVRow> GlobalVariables = new Dictionary<string, GVRow>(StringComparer.InvariantCultureIgnoreCase);

	public ObservableCollection<GVRow> GlobalVariableList { get; set; }

	public bool ReadOnly { get; set; }

	public bool IsEditable => !ReadOnly;

	public event UserPluginMessageEventHandler UserPluginMessage;

	public GlobalVariableViewWPF()
	{
		InitializeComponent();
		UpdateSort(ListSortDirection.Ascending);
		base.DataContext = this;
		GlobalVariableList = new ObservableCollection<GVRow>();
		GlobalVariables = new Dictionary<string, GVRow>(StringComparer.CurrentCultureIgnoreCase);
		LoadVariables(null);
		gvGrid.CurrentCellChanged += gvGrid_CurrentCellChanged;
		gvGrid.LostFocus += gvGrid_LostFocus;
		GlobalVariable.OnGlobalVariableChange += GlobalVariable_OnGlobalVariableChange;
		QSecurity.UserAccessLevelChanged += QSecurity_UserAccessLevelChanged;
	}

	private void gvGrid_LostFocus(object sender, RoutedEventArgs e)
	{
		gvGrid.Refresh();
		ApplyChanges();
	}

	private void gvGrid_CurrentCellChanged(object sender, EventArgs e)
	{
		gvGrid.CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true);
		gvGrid_LostFocus(sender, null);
	}

	private void ApplyChanges()
	{
		try
		{
			bool flag = false;
			if (GlobalVariable.GetGlobalVariable("QSPR_STOP", out var gvValue))
			{
				try
				{
					flag = Convert.ToBoolean(gvValue);
				}
				catch
				{
				}
			}
			bool flag2 = false;
			if (GlobalVariable.GetGlobalVariable("QSPR_ABORT", out var gvValue2))
			{
				try
				{
					flag2 = Convert.ToBoolean(gvValue2);
				}
				catch
				{
				}
			}
			GlobalVariable.GVariables.Clear();
			updatingGlobalVariables = true;
			foreach (GVRow globalVariable in GlobalVariableList)
			{
				try
				{
					string text = globalVariable.GVName.Trim();
					string gvValue3 = globalVariable.GVValue.Trim();
					if (text.Trim().Length > 0)
					{
						GlobalVariable.SetGlobalVariable(text, gvValue3);
					}
				}
				catch
				{
				}
			}
			GlobalVariable.SetGlobalVariable("QSPR_STOP", flag.ToString());
			GlobalVariable.SetGlobalVariable("QSPR_ABORT", flag2.ToString());
			GlobalVariable.SetGlobalVariable("QTM_STOP", flag.ToString());
			GlobalVariable.SetGlobalVariable("QTM_ABORT", flag2.ToString());
		}
		catch
		{
		}
		finally
		{
			updatingGlobalVariables = false;
		}
	}

	private void GlobalVariable_OnGlobalVariableChange(object sender, GlobalVariableEventArgs e)
	{
		LoadVariables(e);
	}

	private void LoadVariables(GlobalVariableEventArgs e)
	{
		if (updatingGlobalVariables)
		{
			return;
		}
		if (gvGrid.InvokeRequired())
		{
			gvGrid.BeginInvoke(delegate
			{
				LoadVariables(e);
			});
			return;
		}
		if (e != null && e.GVName != null)
		{
			UpdateValue(e.GVName, e.GVValue);
			return;
		}
		foreach (string key in GlobalVariable.GVariables.Keys)
		{
			if (GlobalVariable.GetGlobalVariable(key, out var gvValue))
			{
				UpdateValue(key, gvValue);
			}
		}
		RemoveDeletedGlobals();
	}

	private void RemoveDeletedGlobals()
	{
		List<string> list = GlobalVariables.Keys.ToList();
		foreach (string key in GlobalVariable.GVariables.Keys)
		{
			if (list.Contains(key, StringComparer.InvariantCultureIgnoreCase))
			{
				list.Remove(key);
			}
		}
		foreach (string item in list)
		{
			GlobalVariableList.Remove(GlobalVariables[item]);
			GlobalVariables.Remove(item);
		}
	}

	private void AddValue(string gvName, string gvValue)
	{
		try
		{
			GVRow gVRow = new GVRow();
			gVRow.GVName = gvName;
			gVRow.GVValue = gvValue;
			GVRow gVRow2 = gVRow;
			GlobalVariableList.Add(gVRow2);
			GlobalVariables[gvName] = gVRow2;
		}
		catch (Exception)
		{
		}
	}

	private void UpdateValue(string gvName, string gvValue)
	{
		try
		{
			if (updatingGlobalVariables)
			{
				return;
			}
			if (gvGrid.InvokeRequired())
			{
				gvGrid.BeginInvoke(delegate
				{
					UpdateValue(gvName, gvValue);
				});
			}
			else if (!GlobalVariables.ContainsKey(gvName))
			{
				AddValue(gvName, gvValue);
			}
			else
			{
				GlobalVariables[gvName].GVValue = gvValue;
			}
		}
		catch (Exception)
		{
		}
	}

	private void QSecurity_UserAccessLevelChanged(object sender, UserAccessLevelChangedEventArgs e)
	{
		try
		{
			switch (e.UserAccessLevel)
			{
			case AccessLevel.Operator:
				btnAdd.IsEnabled = false;
				btnRemove.IsEnabled = false;
				gvGrid.IsEnabled = false;
				break;
			case AccessLevel.Engineer:
				btnAdd.IsEnabled = true;
				btnRemove.IsEnabled = true;
				gvGrid.IsEnabled = true;
				break;
			case AccessLevel.Technician:
				break;
			}
		}
		catch
		{
		}
	}

	private void btnAdd_Click(object sender, RoutedEventArgs e)
	{
		try
		{
			AddValue("", "");
			gvGrid.Focus();
			gvGrid.SelectedItem = GlobalVariables[""];
			int index = gvGrid.Items.IndexOf(gvGrid.SelectedItem);
			gvGrid.CurrentCell = new DataGridCellInfo(gvGrid.Items[index], gvGrid.Columns[0]);
			gvGrid.BeginEdit();
		}
		catch
		{
		}
	}

	private void btnRemove_Click(object sender, RoutedEventArgs e)
	{
		try
		{
			string text = "";
			if (gvGrid.SelectedItem is GVRow selectedItem)
			{
				MessageBoxResult messageBoxResult = MessageBox.Show(Application.Current.MainWindow, "Do you want to delete the selected Global Variable" + text + " ?", "QSPR Message Center - Warning", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
				if (messageBoxResult == MessageBoxResult.Yes)
				{
					RemoveSelectedRow(selectedItem);
					gvGrid.Refresh();
					ApplyChanges();
				}
			}
		}
		catch
		{
		}
	}

	private void RemoveSelectedRow(GVRow selectedItem)
	{
		if (selectedItem != null)
		{
			GlobalVariables.Remove(selectedItem.GVName);
			GlobalVariableList.Remove(selectedItem);
		}
	}

	private void btnUpdate_Click(object sender, RoutedEventArgs e)
	{
		TTDPluginEventArgs tTDPluginEventArgs = new TTDPluginEventArgs();
		tTDPluginEventArgs.MessageCategory = CallbackCategory.SPECIAL_MESSAGE;
		tTDPluginEventArgs.Key = "Update Global Variables with Tester Config";
		tTDPluginEventArgs.Message = "Update Global Variables";
		OnUserPluginHandler(this, tTDPluginEventArgs);
	}

	protected void OnUserPluginHandler(object sender, TTDPluginEventArgs e)
	{
		if (this.UserPluginMessage != null)
		{
			this.UserPluginMessage(sender, e);
		}
	}

	private void UpdateSort(ListSortDirection? sortDirection = ListSortDirection.Ascending)
	{
		gvGrid.Columns[0].SortDirection = sortDirection;
		gvGrid.Items.SortDescriptions.Clear();
		if (sortDirection.HasValue)
		{
			gvGrid.Items.SortDescriptions.Add(new SortDescription(gvGrid.Columns[0].SortMemberPath, sortDirection.Value));
		}
		gvGrid.Items.Refresh();
	}
}
