using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using QC.GlobalVariableManager;
using QC.QsprShared.Config;
using QC.QsprShared.Dialogs;
using QC.QsprShared.QDARTLogging;
using QC.QsprShared.Trace;
using QC.QTMInterface;
using QC.QTMSecurity;

namespace QC.QTMApplication;

public class DebugWin : DebugWindowPlugIn
{
	private delegate void SetText();

	private const string AUTO_UPDATE = "Auto Update";

	private const string END_OF_TEST = "End Of Test";

	private const string END_OF_UNIT = "End Of Unit";

	private const int NO_LIMIT = -1;

	private const int WM_SETREDRAW = 11;

	private const int WM_USER = 1024;

	private const int EM_GETEVENTMASK = 1083;

	private const int EM_SETEVENTMASK = 1093;

	private const uint WM_VSCROLL = 277u;

	private const int SB_PAGEBOTTOM = 7;

	private string windowName = "";

	private bool wordWrap = true;

	private bool autoScroll = true;

	private bool dateStamp;

	private bool timeStamp;

	private int maxDebugChars = 1800000;

	private FindInfo findInfo = default(FindInfo);

	private int startSearchIndex;

	private bool appendText = true;

	private DateTime appendTimeStamp = DateTime.Now;

	private StringBuilder debugMessageBuffer = new StringBuilder();

	private ToolStrip toolStrip1;

	private ToolStripDropDownButton toolStripDropDownButton1;

	private int eventMask;

	private WorkspaceConfig WConfig;

	private IContainer components;

	private Panel panel2;

	private RichTextBox txtMessages;

	private Timer txtMessagesUpdateTimer;

	private ContextMenuStrip contextMenuDebug;

	private ToolStripMenuItem copyToolStripMenuItem;

	private ToolStripMenuItem selectAllToolStripMenuItem;

	private ToolStripSeparator toolStripSeparator1;

	private ToolStripMenuItem findToolStripMenuItem;

	private ToolStripMenuItem findNextToolStripMenuItem;

	private ToolStripSeparator toolStripSeparator2;

	private ToolStripMenuItem fontToolStripMenuItem;

	private ToolStripMenuItem backgroundColorToolStripMenuItem;

	private ToolStripMenuItem wordWrapToolStripMenuItem;

	private ToolStripMenuItem textLimitToolStripMenuItem;

	private ToolStripSeparator toolStripSeparator3;

	private ToolStripMenuItem autoScrollToolStripMenuItem;

	private ToolStripMenuItem dateStampToolStripMenuItem;

	private ToolStripMenuItem timeStampToolStripMenuItem;

	private ToolStripMenuItem saveToolStripMenuItem;

	private ToolStripMenuItem toolStripMenuItem2;

	private ToolStripSeparator toolStripSeparator5;

	public DateTime AppendTimeStamp
	{
		get
		{
			return appendTimeStamp;
		}
		set
		{
			appendTimeStamp = value;
		}
	}

	public override string Caption => windowName;

	public override bool AppendText
	{
		set
		{
			appendText = value;
		}
	}

	public string WindowName
	{
		set
		{
			windowName = value;
		}
	}

	[DllImport("user32.dll")]
	private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

	public DebugWin(WorkspaceConfig wConfig)
	{
		WConfig = wConfig;
		InitializeComponent();
		ResetToConfigValue();
		QSecurity.UserAccessLevelChanged += QSecurity_UserAccessLevelChanged;
		QSecurity_UserAccessLevelChanged(this, new UserAccessLevelChangedEventArgs(QSecurity.UserAccessLevel));
	}

	private void ResetToConfigValue()
	{
		try
		{
			if (WConfig.RefreshCurrSettings)
			{
				autoScroll = WConfig.AutoScrollDebugWindows;
				autoScrollToolStripMenuItem.Checked = autoScroll;
				timeStamp = WConfig.ShowTimeStamp;
				timeStampToolStripMenuItem.Checked = timeStamp;
				dateStamp = WConfig.ShowDateStamp;
				dateStampToolStripMenuItem.Checked = dateStamp;
				maxDebugChars = WConfig.MaxDisplayDebugCharacters;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ResetToConfigValue failed " + ex.Message, TraceMessageType.Exception);
		}
	}

	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.DebugWin));
		this.panel2 = new System.Windows.Forms.Panel();
		this.toolStrip1 = new System.Windows.Forms.ToolStrip();
		this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton();
		this.txtMessages = new System.Windows.Forms.RichTextBox();
		this.contextMenuDebug = new System.Windows.Forms.ContextMenuStrip(this.components);
		this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
		this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
		this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.findNextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
		this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
		this.fontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.backgroundColorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.textLimitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
		this.wordWrapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.autoScrollToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.dateStampToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.timeStampToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.txtMessagesUpdateTimer = new System.Windows.Forms.Timer(this.components);
		this.panel2.SuspendLayout();
		this.toolStrip1.SuspendLayout();
		this.contextMenuDebug.SuspendLayout();
		base.SuspendLayout();
		this.panel2.Controls.Add(this.toolStrip1);
		this.panel2.Controls.Add(this.txtMessages);
		this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
		this.panel2.Location = new System.Drawing.Point(0, 0);
		this.panel2.Name = "panel2";
		this.panel2.Size = new System.Drawing.Size(584, 278);
		this.panel2.TabIndex = 2;
		this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[1] { this.toolStripDropDownButton1 });
		this.toolStrip1.Location = new System.Drawing.Point(0, 0);
		this.toolStrip1.Name = "toolStrip1";
		this.toolStrip1.Size = new System.Drawing.Size(584, 25);
		this.toolStrip1.TabIndex = 2;
		this.toolStrip1.Text = "toolStrip1";
		this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
		this.toolStripDropDownButton1.DropDown = this.contextMenuDebug;
		this.toolStripDropDownButton1.Image = (System.Drawing.Image)resources.GetObject("toolStripDropDownButton1.Image");
		this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.toolStripDropDownButton1.Name = "toolStripDropDownButton1";
		this.toolStripDropDownButton1.Size = new System.Drawing.Size(62, 22);
		this.toolStripDropDownButton1.Text = "Options";
		this.txtMessages.AcceptsTab = true;
		this.txtMessages.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.txtMessages.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
		this.txtMessages.ContextMenuStrip = this.contextMenuDebug;
		this.txtMessages.Location = new System.Drawing.Point(3, 24);
		this.txtMessages.Name = "txtMessages";
		this.txtMessages.ReadOnly = true;
		this.txtMessages.Size = new System.Drawing.Size(578, 254);
		this.txtMessages.TabIndex = 0;
		this.txtMessages.Text = "";
		this.txtMessages.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(txtMessages_LinkClicked);
		this.contextMenuDebug.Items.AddRange(new System.Windows.Forms.ToolStripItem[17]
		{
			this.saveToolStripMenuItem, this.toolStripSeparator5, this.copyToolStripMenuItem, this.selectAllToolStripMenuItem, this.toolStripSeparator1, this.findToolStripMenuItem, this.findNextToolStripMenuItem, this.toolStripSeparator2, this.toolStripMenuItem2, this.fontToolStripMenuItem,
			this.backgroundColorToolStripMenuItem, this.textLimitToolStripMenuItem, this.toolStripSeparator3, this.wordWrapToolStripMenuItem, this.autoScrollToolStripMenuItem, this.dateStampToolStripMenuItem, this.timeStampToolStripMenuItem
		});
		this.contextMenuDebug.Name = "contextMenuDebug";
		this.contextMenuDebug.OwnerItem = this.toolStripDropDownButton1;
		this.contextMenuDebug.Size = new System.Drawing.Size(200, 336);
		this.contextMenuDebug.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(contextMenuDebug_ItemClicked);
		this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
		this.saveToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.saveToolStripMenuItem.Text = "Save";
		this.toolStripSeparator5.Name = "toolStripSeparator5";
		this.toolStripSeparator5.Size = new System.Drawing.Size(196, 6);
		this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
		this.copyToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.C | System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.Control;
		this.copyToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.copyToolStripMenuItem.Text = "Copy";
		this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
		this.selectAllToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.A | System.Windows.Forms.Keys.Control;
		this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.selectAllToolStripMenuItem.Text = "Select All";
		this.toolStripSeparator1.Name = "toolStripSeparator1";
		this.toolStripSeparator1.Size = new System.Drawing.Size(196, 6);
		this.findToolStripMenuItem.Name = "findToolStripMenuItem";
		this.findToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F | System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.Control;
		this.findToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.findToolStripMenuItem.Text = "Find...";
		this.findNextToolStripMenuItem.Name = "findNextToolStripMenuItem";
		this.findNextToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F3 | System.Windows.Forms.Keys.Shift;
		this.findNextToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.findNextToolStripMenuItem.Text = "Find Next";
		this.toolStripSeparator2.Name = "toolStripSeparator2";
		this.toolStripSeparator2.Size = new System.Drawing.Size(196, 6);
		this.toolStripMenuItem2.Name = "toolStripMenuItem2";
		this.toolStripMenuItem2.ShortcutKeys = System.Windows.Forms.Keys.Delete | System.Windows.Forms.Keys.Shift;
		this.toolStripMenuItem2.Size = new System.Drawing.Size(199, 22);
		this.toolStripMenuItem2.Text = "Clear All Text";
		this.fontToolStripMenuItem.Name = "fontToolStripMenuItem";
		this.fontToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.fontToolStripMenuItem.Text = "Font...";
		this.backgroundColorToolStripMenuItem.Name = "backgroundColorToolStripMenuItem";
		this.backgroundColorToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.backgroundColorToolStripMenuItem.Text = "Background Color";
		this.textLimitToolStripMenuItem.Name = "textLimitToolStripMenuItem";
		this.textLimitToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.textLimitToolStripMenuItem.Text = "Text Limit...";
		this.toolStripSeparator3.Name = "toolStripSeparator3";
		this.toolStripSeparator3.Size = new System.Drawing.Size(196, 6);
		this.wordWrapToolStripMenuItem.Checked = true;
		this.wordWrapToolStripMenuItem.CheckOnClick = true;
		this.wordWrapToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
		this.wordWrapToolStripMenuItem.Name = "wordWrapToolStripMenuItem";
		this.wordWrapToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.wordWrapToolStripMenuItem.Text = "Word Wrap";
		this.autoScrollToolStripMenuItem.Checked = true;
		this.autoScrollToolStripMenuItem.CheckOnClick = true;
		this.autoScrollToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
		this.autoScrollToolStripMenuItem.Name = "autoScrollToolStripMenuItem";
		this.autoScrollToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.S | System.Windows.Forms.Keys.Alt;
		this.autoScrollToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.autoScrollToolStripMenuItem.Text = "Auto-Scroll";
		this.dateStampToolStripMenuItem.CheckOnClick = true;
		this.dateStampToolStripMenuItem.Name = "dateStampToolStripMenuItem";
		this.dateStampToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.dateStampToolStripMenuItem.Text = "Date Stamp";
		this.timeStampToolStripMenuItem.CheckOnClick = true;
		this.timeStampToolStripMenuItem.Name = "timeStampToolStripMenuItem";
		this.timeStampToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
		this.timeStampToolStripMenuItem.Text = "Time Stamp";
		this.txtMessagesUpdateTimer.Enabled = true;
		this.txtMessagesUpdateTimer.Interval = 800;
		this.txtMessagesUpdateTimer.Tick += new System.EventHandler(txtMessagesUpdateTimer_Tick);
		base.Controls.Add(this.panel2);
		base.Name = "DebugWin";
		base.Size = new System.Drawing.Size(584, 278);
		base.Load += new System.EventHandler(DebugWin_Load);
		this.panel2.ResumeLayout(false);
		this.panel2.PerformLayout();
		this.toolStrip1.ResumeLayout(false);
		this.toolStrip1.PerformLayout();
		this.contextMenuDebug.ResumeLayout(false);
		base.ResumeLayout(false);
	}

	private void txtMessagesUpdateTimer_Tick(object sender, EventArgs e)
	{
		if (txtMessages.TextLength > 0 && maxDebugChars != -1 && debugMessageBuffer.Length + txtMessages.TextLength > maxDebugChars)
		{
			DumpOldCharacters();
			GC.Collect();
		}
		if (debugMessageBuffer.Length <= 0 || !(WConfig.DebugWindowUpdateOption == "Auto Update"))
		{
			return;
		}
		if (autoScroll)
		{
			txtMessages.AppendText(debugMessageBuffer.ToString());
			ScrollDebugWindowToRecentText();
		}
		else
		{
			int selectionStart = txtMessages.SelectionStart;
			int selectionLength = txtMessages.SelectionLength;
			bool focused = txtMessages.Focused;
			if (focused)
			{
				base.Parent.Focus();
			}
			txtMessages.AppendText(debugMessageBuffer.ToString());
			txtMessages.SelectionStart = selectionStart;
			txtMessages.SelectionLength = selectionLength;
			if (focused)
			{
				txtMessages.Focus();
			}
		}
		debugMessageBuffer.Length = 0;
	}

	private void ScrollDebugWindowToRecentText()
	{
		if (autoScroll)
		{
			SendMessage(txtMessages.Handle, 277u, 7, 0);
		}
	}

	private void DumpOldCharacters()
	{
		int num = maxDebugChars / 3;
		int textLength = txtMessages.TextLength;
		int num2 = num * 2;
		if (textLength - num > num2)
		{
			num = textLength - num2;
		}
		if (textLength > num + 1)
		{
			StopRepaint();
			txtMessages.Select(0, num);
			if (WConfig.SaveAllDebugWindows || WConfig.SaveDebugOnlyOnFail)
			{
				string selectedText = txtMessages.SelectedText;
				string debugFileName = GetDebugFileName(WConfig.LastUsedSerialNumber, WConfig.SaveInSubFolders);
				SaveMessages(debugFileName, selectedText);
			}
			txtMessages.ReadOnly = false;
			txtMessages.SelectedText = "";
			txtMessages.ReadOnly = true;
			txtMessages.SelectionStart = txtMessages.TextLength + 1;
			StartRepaint();
		}
	}

	private void StopRepaint()
	{
		SendMessage(txtMessages.Handle, 11u, 0, 0);
		eventMask = SendMessage(txtMessages.Handle, 1083u, 0, 0);
	}

	private void StartRepaint()
	{
		SendMessage(txtMessages.Handle, 1093u, 0, eventMask);
		SendMessage(txtMessages.Handle, 11u, 1, 0);
		txtMessages.Invalidate();
	}

	private void DebugWin_Load(object sender, EventArgs e)
	{
		txtMessagesUpdateTimer.Start();
	}

	public void OnTextOut(string strWindowName, string strWindowText)
	{
		if (dateStamp || timeStamp)
		{
			strWindowText = strWindowText.TrimEnd('\n');
			strWindowText = strWindowText.Replace("\n", $"\n{GetDateStamp()} {GetTimeStamp()}: ");
			strWindowText = $"{GetDateStamp()} {GetTimeStamp()}: " + strWindowText + "\n";
		}
		debugMessageBuffer.Append(strWindowText);
	}

	private string GetDateStamp()
	{
		if (!dateStamp)
		{
			return "";
		}
		return DateTime.Now.ToString("MM-dd-yyyy");
	}

	private string GetTimeStamp()
	{
		if (!timeStamp)
		{
			return "";
		}
		return DateTime.Now.ToString("hh:mm:ss:fff");
	}

	private void ultraBtnSave_Click(object sender, EventArgs e)
	{
		SaveFileDialog saveFileDialog = new SaveFileDialog();
		saveFileDialog.Filter = "Text Format|*.txt";
		saveFileDialog.Title = "Saving Text";
		saveFileDialog.OverwritePrompt = true;
		saveFileDialog.ShowDialog();
		if (saveFileDialog.FileName != "")
		{
			try
			{
				SaveMessages(saveFileDialog.FileName);
			}
			catch (Exception ex)
			{
				AppMessageDialog.Show("Save Error (Debug) : " + ex.Message, DialogResult.OK, MessageDialogType.Exception);
			}
		}
	}

	private void ClearText()
	{
		if (txtMessages.InvokeRequired)
		{
			BeginInvoke((MethodInvoker)delegate
			{
				ClearText();
			});
		}
		else
		{
			txtMessages.Clear();
		}
	}

	public override bool MenuMessages(string menu)
	{
		switch (menu)
		{
		case "Open":
		case "New":
		case "Reset All":
		case "Clear Debug Windows":
			ClearText();
			break;
		case "Save Debug Windows":
			SaveWindow(WConfig.LastUsedSerialNumber, WConfig.SaveInSubFolders);
			break;
		}
		return true;
	}

	public override void OnConfigInfo(WSpaceConfig wsc)
	{
		base.wsc = wsc;
		if (wsc.Font != null)
		{
			txtMessages.Font = wsc.Font;
		}
		ResetToConfigValue();
	}

	public void SaveWindow(string unitSerial, bool saveInSubFolder)
	{
		string debugFileName = GetDebugFileName(unitSerial, saveInSubFolder);
		SaveMessages(debugFileName);
	}

	private string GetLogType()
	{
		if (windowName == "Error")
		{
			return "TXT-Error";
		}
		if (windowName == "Log")
		{
			return "TXT-Log";
		}
		return "TXT-Debug";
	}

	private string GetDebugFileName(string unitSerial, bool saveInSubFolder)
	{
		LoggingConfigurations loggingConfigurations = new LoggingConfigurations();
		if (loggingConfigurations.UseGlobalConfiguration())
		{
			string logType = GetLogType();
			LogConfigInput input = new LogConfigInput(QTMGlobalVariable.GVariables, logType);
			return loggingConfigurations.GetLogFilePath(input) + ".txt";
		}
		string text = WConfig.DebugWindowSaveLocation;
		if (!Directory.Exists(text))
		{
			try
			{
				Directory.CreateDirectory(text);
			}
			catch (Exception ex)
			{
				TraceMessage.Write(ToString(), "\nCan't create the directory, writing to default location " + Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), QSPRMainWindow.FeatureConfigInfo.LogDirectory) + ex.Message, TraceMessageType.Exception);
				text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), QSPRMainWindow.FeatureConfigInfo.LogDirectory);
			}
		}
		if (saveInSubFolder)
		{
			text = text + "\\" + Caption;
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
		}
		DateTime now = DateTime.Now;
		if (appendText)
		{
			now = AppendTimeStamp;
		}
		else
		{
			appendTimeStamp = now;
		}
		string text2 = now.Month + "-" + now.Day + "-" + now.Year + " " + now.Hour + "_" + now.Minute + "_" + now.Second + "_" + now.Millisecond;
		return text + "\\" + unitSerial + " - " + Caption + " - " + text2 + ".txt";
	}

	private void SaveMessages(string filename, string messages)
	{
		try
		{
			string directoryName = Path.GetDirectoryName(filename);
			Directory.CreateDirectory(directoryName);
			using StreamWriter streamWriter = new StreamWriter(filename, appendText);
			List<string> list = new List<string>(messages.Split('\n'));
			foreach (string item in list)
			{
				streamWriter.WriteLine(item);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SaveMessages " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void SaveMessages(string fileName)
	{
		if (base.InvokeRequired)
		{
			BeginInvoke((MethodInvoker)delegate
			{
				SaveMessages(fileName);
			});
		}
		else if (txtMessages.TextLength > 0)
		{
			SaveMessages(fileName, txtMessages.Text.ToString());
		}
	}

	public override void DebugText(string winName, string strWindowText)
	{
	}

	public override void OnMsg(ArrayList message)
	{
		TraceMessage.Write(ToString(), "OnMsg " + Caption, TraceMessageType.Trace);
		try
		{
			foreach (MsgData item in message)
			{
				ProcessMessage(item);
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "OnMsg " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void UpdateWindow()
	{
		try
		{
			SetText method = SetWindowText;
			BeginInvoke(method);
		}
		catch
		{
		}
	}

	private void SetWindowText()
	{
		try
		{
			if (WConfig.ShowDebugMessages)
			{
				txtMessages.SuspendLayout();
				txtMessages.Font = wsc.Font;
				txtMessages.AppendText(debugMessageBuffer.ToString());
				ScrollDebugWindowToRecentText();
				txtMessages.ResumeLayout();
				debugMessageBuffer.Length = 0;
			}
		}
		catch
		{
		}
	}

	public void ProcessMessage(MsgData msgData)
	{
		TraceMessage.Write(ToString(), "ProcessMessage " + msgData.msgType, TraceMessageType.Trace);
		try
		{
			switch (msgData.msgType)
			{
			case TestMsgType.OnUnitStart:
				AppendTimeStamp = DateTime.Now;
				ClearText();
				break;
			case TestMsgType.OnUnitEnd:
				if (WConfig.DebugWindowUpdateOption.ToUpper() == "End Of Unit".ToUpper())
				{
					UpdateWindow();
				}
				if ((!WConfig.SaveDebugOnlyOnFail || msgData.Result != TestResult.Passed) && WConfig.SaveAllDebugWindows && windowName.ToUpper() != "TEMP")
				{
					SaveWindow(msgData.TestFullPath, WConfig.SaveInSubFolders);
				}
				break;
			case TestMsgType.OnTestResult:
				if (WConfig.DebugWindowUpdateOption.ToUpper() == "End Of Test".ToUpper())
				{
					UpdateWindow();
				}
				break;
			}
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "ProcessMessage " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void QSecurity_UserAccessLevelChanged(object sender, UserAccessLevelChangedEventArgs e)
	{
		try
		{
			switch (e.UserAccessLevel)
			{
			case AccessLevel.Technician:
			case AccessLevel.Engineer:
				txtMessages.ReadOnly = true;
				break;
			case AccessLevel.Operator:
				txtMessages.ReadOnly = true;
				break;
			}
		}
		catch
		{
		}
	}

	private void txtMessages_LinkClicked(object sender, LinkClickedEventArgs e)
	{
		try
		{
			Process.Start(e.LinkText);
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show("Failed to open file, " + ex.Message, DialogResult.OK, MessageDialogType.Information);
		}
	}

	private void contextMenuDebug_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
	{
		contextMenuDebug.Close();
		HandleMenuClick(e);
	}

	private void HandleMenuClick(ToolStripItemClickedEventArgs e)
	{
		try
		{
			switch (e.ClickedItem.Text)
			{
			case "Save":
			{
				SaveFileDialog saveFileDialog = new SaveFileDialog();
				saveFileDialog.Filter = "Log File (*.txt)|*.txt";
				saveFileDialog.Title = "Save a log File";
				string debugFileName = GetDebugFileName(WConfig.LastUsedSerialNumber, WConfig.SaveInSubFolders);
				saveFileDialog.FileName = Path.GetFileName(debugFileName);
				saveFileDialog.InitialDirectory = Path.GetDirectoryName(debugFileName);
				saveFileDialog.DefaultExt = "txt";
				saveFileDialog.ShowDialog();
				if (saveFileDialog.FileName != "")
				{
					SaveMessages(saveFileDialog.FileName);
				}
				break;
			}
			case "Copy":
				Clipboard.SetText(txtMessages.SelectedText);
				break;
			case "Select All":
				txtMessages.SelectAll();
				break;
			case "Clear All Text":
				ClearText();
				break;
			case "Font...":
			{
				FontDialog fontDialog = new FontDialog();
				fontDialog.ShowColor = true;
				fontDialog.Font = txtMessages.Font;
				fontDialog.Color = txtMessages.ForeColor;
				if (fontDialog.ShowDialog() != DialogResult.Cancel)
				{
					txtMessages.Font = fontDialog.Font;
					txtMessages.ForeColor = fontDialog.Color;
				}
				break;
			}
			case "Background Color":
			{
				ColorDialog colorDialog = new ColorDialog();
				colorDialog.Color = txtMessages.BackColor;
				if (colorDialog.ShowDialog() != DialogResult.Cancel)
				{
					txtMessages.BackColor = colorDialog.Color;
				}
				break;
			}
			case "Word Wrap":
				wordWrap = !wordWrap;
				txtMessages.WordWrap = wordWrap;
				break;
			case "Text Limit...":
			{
				TextLimitDialog textLimitDialog = new TextLimitDialog(maxDebugChars);
				if (textLimitDialog.ShowDialog() == DialogResult.OK)
				{
					maxDebugChars = textLimitDialog.MaxDisplayDebugCharacters;
				}
				break;
			}
			case "Find...":
			{
				startSearchIndex = txtMessages.SelectionStart;
				FindDialog findDialog = new FindDialog(findInfo);
				findDialog.FindNextEvent += SearchDebugTextEvent;
				findDialog.Show();
				break;
			}
			case "Find Next":
				HightLightSearchText();
				break;
			case "Auto-Scroll":
				autoScroll = !autoScroll;
				break;
			case "Date Stamp":
				dateStamp = !dateStamp;
				break;
			case "Time Stamp":
				timeStamp = !timeStamp;
				break;
			}
		}
		catch (Exception ex)
		{
			AppMessageDialog.Show($"Failed to {e.ClickedItem.Text}, {ex.Message}", DialogResult.OK, MessageDialogType.Information);
		}
	}

	private void SearchDebugTextEvent(FindInfo info)
	{
		try
		{
			if (base.InvokeRequired)
			{
				BeginInvoke((MethodInvoker)delegate
				{
					SearchDebugTextEvent(info);
				});
				return;
			}
			if (string.Compare(findInfo.SearchText, info.SearchText) != 0)
			{
				startSearchIndex = 0;
			}
			findInfo = info;
			HightLightSearchText();
		}
		catch (Exception ex)
		{
			TraceMessage.Write(ToString(), "SearchDebugTextEvent failed, " + ex.Message, TraceMessageType.Exception);
		}
	}

	private void HightLightSearchText()
	{
		txtMessages.SuspendLayout();
		if (startSearchIndex > 0)
		{
			txtMessages.Undo();
		}
		if (txtMessages.TextLength > 0 && startSearchIndex >= 0)
		{
			int num = -1;
			RichTextBoxFinds richTextBoxFinds = RichTextBoxFinds.None;
			if (findInfo.MatchCase)
			{
				richTextBoxFinds = RichTextBoxFinds.MatchCase;
			}
			if (findInfo.MatchWholeWordOnly)
			{
				richTextBoxFinds |= RichTextBoxFinds.WholeWord;
			}
			num = txtMessages.Find(findInfo.SearchText, startSearchIndex, richTextBoxFinds);
			if (num >= 0)
			{
				txtMessages.Focus();
				txtMessages.Select(num, findInfo.SearchText.Length);
				startSearchIndex = num + findInfo.SearchText.Length;
			}
			else if (AppMessageDialog.Show("Text not found.  Do you want to start searching from the beginning?", "QSPR - Message Center", MessageBoxButtons.OKCancel, DialogResult.Cancel, MessageDialogType.CriticalWarning) == DialogResult.OK)
			{
				startSearchIndex = 0;
				HightLightSearchText();
			}
		}
		txtMessages.ResumeLayout();
		txtMessages.Refresh();
	}
}
