using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using MultiLanguageManger;
using QC.QMSCT.Language;
using Qualcomm.GUI.Controls;

namespace QC.QMSCT;

public class ConfigPanel : UserControl
{
	private delegate void DisplayStatusDelegate(string statusText);

	private delegate void TestItemStartedDelegate(string testName);

	private delegate void TestItemDoneDelegate(string testName, TestResult testResult);

	public delegate void ZoomSelect(bool isSelected, int panelNumber);

	public delegate void UnitConnected(object obj, bool connected);

	public delegate void ExecutionCompleted(object obj);

	public delegate void ModifyXttTimeout(string timeout);

	public enum DetectionInstance
	{
		DETECT_INST_PORT_NO,
		DETECT_INST_PHY_ADDR,
		DETECT_INST_NET_MODE
	}

	private const string saveString = "Save Debug Messages";

	private const string showUnitProgrammerString = "Show Unit Programmer";

	private const string hideUnitProgrammerString = "Hide Unit Programmer";

	private const string stopQSPRTestString = "Stop QSPR Test";

	private IContainer components;

	private QMSCTMultiLanguageManger language = new QMSCTMultiLanguageManger();

	private QMSCTMultiLanguageManger.Language currentLang;

	private string currentTestName = "";

	private Queue<string> outputTextQueue = new Queue<string>();

	private StringBuilder logMessages = new StringBuilder();

	private PanelStat panelStats = new PanelStat();

	private object logMessagesLock = new object();

	private object StatusMessagesLock = new object();

	public bool runningRoundRobinExecution;

	private int old_XttTimeout;

	private string logFile = "";

	private string logFileDir = "C:\\Qualcomm\\QMSCT\\Log";

	private Splitter splitter1;

	private Splitter splitter2;

	private Splitter splitter3;

	private TestPanel testPanel;

	private System.Windows.Forms.Timer timer1;

	private DetectionInstance detectionInstance;

	private int expectedCOMPortAtStart;

	private int expectedCOMPortAfterPowerCycle;

	private string expectedPhysicalAddress = "";

	private bool testRunning;

	private bool testCompleted;

	private string waitingForInfoTag = "serial number";

	private string title = "Mode1,Mode2";

	public bool uutConnected;

	public int comPort;

	public IUnitProgrammer unitProgrammer;

	public QMSCTMultiLanguageManger.Language CurrentLanguage
	{
		get
		{
			return currentLang;
		}
		set
		{
			currentLang = value;
			language.CurrentLanguage = currentLang;
		}
	}

	public bool SNProvidedByEngine => unitProgrammer.GenericSetup.SNProvidedByEngine;

	public DetectionInstance DetectionInstanceValue
	{
		set
		{
			detectionInstance = value;
		}
	}

	public int ExpectedCOMPortAtStart
	{
		get
		{
			return expectedCOMPortAtStart;
		}
		set
		{
			expectedCOMPortAtStart = value;
		}
	}

	public int ExpectedCOMPortAfterPowerCycle
	{
		get
		{
			return expectedCOMPortAfterPowerCycle;
		}
		set
		{
			expectedCOMPortAfterPowerCycle = value;
		}
	}

	public string ExpectedPhysicalAddress
	{
		get
		{
			return expectedPhysicalAddress;
		}
		set
		{
			expectedPhysicalAddress = value;
		}
	}

	public override Color BackColor
	{
		get
		{
			return testPanel.BackColor;
		}
		set
		{
			testPanel.BackColor = value;
		}
	}

	public override Color ForeColor
	{
		get
		{
			return testPanel.ForeColor;
		}
		set
		{
			testPanel.ForeColor = value;
		}
	}

	public bool ReadOnly
	{
		get
		{
			return testPanel.ReadOnly;
		}
		set
		{
			testPanel.ReadOnly = value;
			testPanel.EnableFlashingSelect = !value;
			base.TabStop = !value;
		}
	}

	public int PanelNumber
	{
		get
		{
			return testPanel.PanelNumber;
		}
		set
		{
			testPanel.PanelNumber = value;
		}
	}

	public bool TestRunning
	{
		get
		{
			return testRunning;
		}
		set
		{
			testRunning = value;
		}
	}

	public bool TestCompleted
	{
		get
		{
			return testCompleted;
		}
		set
		{
			testCompleted = value;
		}
	}

	public string WaitingForInfoTag
	{
		get
		{
			return waitingForInfoTag;
		}
		set
		{
			waitingForInfoTag = value;
		}
	}

	public string Title
	{
		get
		{
			return title;
		}
		set
		{
			title = value;
		}
	}

	public bool UUTConnected => uutConnected;

	public event ZoomSelect OnZoomSelect;

	public event UnitConnected OnUnitConnected;

	public event ExecutionCompleted OnExecutionCompleted;

	public event ModifyXttTimeout OnModifyTestTimeout;

	public ConfigPanel()
	{
		InitializeComponent();
		testPanel.OnSerialNumberEntered += testPanel_OnSerialNumberEntered;
		testPanel.OnInfoEntered += testPanel_OnInfoEntered;
		testPanel.OnZoomSelect += testPanel_OnZoomSelect;
		testPanel.OnUserResponse += testPanel_OnUserResponse;
		testPanel.OnStopButtonPressed += testPanel_OnStopButtonPressed;
		testPanel.OnStartButtonPressed += testPanel_OnStartButtonPressed;
		ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem();
		toolStripMenuItem.Enabled = true;
		toolStripMenuItem.Name = "Save Debug Messages";
		toolStripMenuItem.Text = "Save Debug Messages";
		toolStripMenuItem.Click += saveItem_Click;
		ToolStripMenuItem toolStripMenuItem2 = new ToolStripMenuItem();
		toolStripMenuItem2.Enabled = false;
		toolStripMenuItem2.Name = "Show Unit Programmer";
		toolStripMenuItem2.Text = "Show Unit Programmer";
		toolStripMenuItem2.Click += showQSPRItem_Click;
		ToolStripMenuItem toolStripMenuItem3 = new ToolStripMenuItem();
		toolStripMenuItem3.Enabled = false;
		toolStripMenuItem3.Name = "Hide Unit Programmer";
		toolStripMenuItem3.Text = "Hide Unit Programmer";
		toolStripMenuItem3.Click += hideQSPRItem_Click;
		ContextMenuStrip = new ContextMenuStrip();
		ContextMenuStrip.Items.Add(toolStripMenuItem);
		ContextMenuStrip.Items.Add(toolStripMenuItem2);
		ContextMenuStrip.Items.Add(toolStripMenuItem3);
		if (!Directory.Exists(logFileDir))
		{
			Directory.CreateDirectory(logFileDir);
		}
		logFileDir = Path.Combine(logFileDir, "Panel" + PanelNumber);
		if (!Directory.Exists(logFileDir))
		{
			Directory.CreateDirectory(logFileDir);
		}
	}

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

	private void InitializeComponent()
	{
		this.components = new System.ComponentModel.Container();
		this.splitter1 = new System.Windows.Forms.Splitter();
		this.splitter2 = new System.Windows.Forms.Splitter();
		this.splitter3 = new System.Windows.Forms.Splitter();
		this.timer1 = new System.Windows.Forms.Timer(this.components);
		this.testPanel = new Qualcomm.GUI.Controls.TestPanel();
		base.SuspendLayout();
		this.splitter1.BackColor = System.Drawing.SystemColors.Control;
		this.splitter1.Dock = System.Windows.Forms.DockStyle.Top;
		this.splitter1.Location = new System.Drawing.Point(0, 0);
		this.splitter1.Name = "splitter1";
		this.splitter1.Size = new System.Drawing.Size(301, 3);
		this.splitter1.TabIndex = 5;
		this.splitter1.TabStop = false;
		this.splitter2.BackColor = System.Drawing.SystemColors.Control;
		this.splitter2.Enabled = false;
		this.splitter2.Location = new System.Drawing.Point(0, 3);
		this.splitter2.Name = "splitter2";
		this.splitter2.Size = new System.Drawing.Size(3, 245);
		this.splitter2.TabIndex = 8;
		this.splitter2.TabStop = false;
		this.splitter3.BackColor = System.Drawing.SystemColors.Control;
		this.splitter3.Dock = System.Windows.Forms.DockStyle.Right;
		this.splitter3.Enabled = false;
		this.splitter3.Location = new System.Drawing.Point(298, 3);
		this.splitter3.Name = "splitter3";
		this.splitter3.Size = new System.Drawing.Size(3, 245);
		this.splitter3.TabIndex = 10;
		this.splitter3.TabStop = false;
		this.timer1.Enabled = true;
		this.timer1.Interval = 1000;
		this.timer1.Tick += new System.EventHandler(timer1_Tick);
		this.testPanel.AutoClearBanner = false;
		this.testPanel.Dock = System.Windows.Forms.DockStyle.Fill;
		this.testPanel.EnableFlashingSelect = true;
		this.testPanel.EnablePanelNumber = true;
		this.testPanel.EnableProgressBar = true;
		this.testPanel.EnableZoomSelect = true;
		this.testPanel.Location = new System.Drawing.Point(3, 3);
		this.testPanel.Name = "testPanel";
		this.testPanel.PanelNumber = 1;
		this.testPanel.ReadOnly = false;
		this.testPanel.Size = new System.Drawing.Size(295, 245);
		this.testPanel.TabIndex = 11;
		this.testPanel.TextOutput = "";
		this.testPanel.TextSerialNumber = "";
		this.testPanel.TextStatus = "";
		base.Controls.Add(this.testPanel);
		base.Controls.Add(this.splitter3);
		base.Controls.Add(this.splitter2);
		base.Controls.Add(this.splitter1);
		base.Name = "ConfigPanel";
		base.Size = new System.Drawing.Size(301, 248);
		base.ResumeLayout(false);
	}

	public void DisableTabs()
	{
	}

	public void EnableTabs()
	{
	}

	public void ClearTestResults()
	{
		StopBanner();
		testPanel.TextSerialNumber = "";
	}

	public string GetSerialNumber()
	{
		return testPanel.TextSerialNumber;
	}

	public void SetSerialNumber(string newSerialNumber)
	{
		testPanel.TextSerialNumber = newSerialNumber;
	}

	public void SetSerialNumber_ReadOnly()
	{
		testPanel.ReadOnly_TextSerialNumber = true;
	}

	public void FocusSerialNumber()
	{
		if (!SNProvidedByEngine)
		{
			testPanel.FocusSerialNumber();
		}
	}

	public void StartGetInfo(string tag, string message)
	{
		WaitingForInfoTag = tag;
		testPanel.StartGetInfo(tag, message);
	}

	public void EndGetInfo()
	{
		testPanel.EndGetInfo();
		WaitingForInfoTag = "serial number";
	}

	public void DisplayStatus(string statusText)
	{
		if (testPanel.InvokeRequired)
		{
			DisplayStatusDelegate method = DisplayStatus;
			testPanel.Invoke(method, statusText);
		}
		else
		{
			string text = statusText + "\n";
			testPanel.AppendColorText(text, Color.Black);
		}
	}

	public void TestItemStarted(string testName)
	{
		if (testPanel.InvokeRequired)
		{
			TestItemStartedDelegate method = TestItemStarted;
			testPanel.Invoke(method, testName);
			return;
		}
		lock (StatusMessagesLock)
		{
			testPanel.AppendColorText("RUN:\t", Color.Yellow);
			string text = testName + "\n";
			testPanel.AppendColorText(text, Color.Black);
			currentTestName = testName;
		}
	}

	public void TestItemDone(string testName, TestResult testResult)
	{
		if (testPanel.InvokeRequired)
		{
			TestItemDoneDelegate method = TestItemDone;
			testPanel.Invoke(method, testName, testResult);
			return;
		}
		lock (StatusMessagesLock)
		{
			if (currentTestName == testName)
			{
				testPanel.RemoveSelectionText("RUN:\t" + testName + "\n");
				switch (testResult)
				{
				case TestResult.Passed:
					testPanel.AppendColorText("PASS:\t", Color.DarkGreen);
					break;
				case TestResult.Failed:
					testPanel.AppendColorText("FAIL:\t", Color.DarkRed);
					break;
				}
				string text = DateTime.Now.ToString("hh:mm:ss:fff") + ",\t" + testName + "\n";
				testPanel.AppendColorText(text, Color.Black);
				currentTestName = "";
			}
		}
	}

	public void StartBanner(string BannerText, Color BannerColor)
	{
		testPanel.StartBanner(BannerText, BannerColor);
	}

	public void StopBanner()
	{
		testPanel.StopBanner();
	}

	public void UpdateAnimations()
	{
		testPanel.UpdateAnimations();
	}

	public void UpdateAnimations(uint Counter)
	{
		testPanel.UpdateAnimations(Counter);
	}

	public void UpdateTestPanelLanguage()
	{
		testPanel.UpdateLanguage();
	}

	public void WriteLine(string text)
	{
		if (!ProcessOutputText(text))
		{
			return;
		}
		lock (logMessagesLock)
		{
			if (logMessages.Length > 0)
			{
				text = "\r\n" + text;
			}
			logMessages.Append(text);
			if (unitProgrammer.GenericSetup.SaveMessagesToFile && logFile != "")
			{
				File.AppendAllText(logFile, text);
			}
		}
	}

	protected bool ProcessOutputText(string text)
	{
		return true;
	}

	protected void UpdateTabs()
	{
		RemoveAllTabPages();
		MatchCollection matchCollection = DelimiterParser.ParseText(title, ",");
		foreach (Match item in matchCollection)
		{
			AddTabPage(item.ToString());
		}
	}

	protected void RemoveAllTabPages()
	{
	}

	protected void AddTabPage(string PageName)
	{
		TabPage tabPage = new TabPage(PageName);
		Label label = new Label();
		label.Dock = DockStyle.Fill;
		label.Font = new Font("Comic Sans MS", 14f, FontStyle.Bold, GraphicsUnit.Point, 0);
		label.ForeColor = Color.Black;
		label.Text = PageName;
		label.TextAlign = ContentAlignment.MiddleCenter;
		tabPage.Controls.Add(label);
	}

	protected void DrawSelectionBars()
	{
	}

	public void Security_EnableContextMenu(bool enable)
	{
		try
		{
			if (!enable)
			{
				HideQspr();
			}
			ContextMenuStrip.Items["Show Unit Programmer"].Visible = enable;
			ContextMenuStrip.Items["Hide Unit Programmer"].Visible = enable;
		}
		catch
		{
		}
	}

	private void tabProvisionModes_SelectedIndexChanged(object sender, EventArgs e)
	{
	}

	private void pictureBox1_SizeChanged(object sender, EventArgs e)
	{
		DrawSelectionBars();
	}

	private void testPanel_OnSerialNumberEntered(string serialNumber, int panelNumber)
	{
		if (!SNProvidedByEngine && serialNumber.Length > 0)
		{
			StartProgrammingUnit(serialNumber);
		}
	}

	private void testPanel_OnInfoEntered(string tag, string info, int panelNumber)
	{
	}

	private void testPanel_OnZoomSelect(bool isSelected, int panelNumber)
	{
		this.OnZoomSelect(isSelected, panelNumber);
	}

	private void testPanel_OnUserResponse(DialogResult response, int panelNumber)
	{
	}

	private void testPanel_OnStopButtonPressed(int panelNumber)
	{
		if (MessageBox.Show(string.Format(CommonResource.BoxMsgStopTest, PanelNumber.ToString()), CommonResource.BoxTitleStopTest, MessageBoxButtons.YesNo) == DialogResult.Yes)
		{
			unitProgrammer.StopUnitProgrammer();
			testPanel.UpdateStatus(TestPanel.PanelStatus.Aborted);
		}
	}

	private void testPanel_OnStartButtonPressed(string serialNumber, int panelNumber)
	{
		if (!SNProvidedByEngine && serialNumber.Length > 0)
		{
			StartProgrammingUnit(serialNumber);
		}
		else
		{
			StartProgrammingUnit("NA");
		}
	}

	private void timer1_Tick(object sender, EventArgs e)
	{
		lock (logMessagesLock)
		{
			if (logMessages.Length > 0)
			{
				testPanel.WriteLine(logMessages.ToString());
				logMessages = new StringBuilder();
			}
		}
	}

	private void saveItem_Click(object sender, EventArgs e)
	{
		Thread thread = new Thread(SaveItemThread);
		thread.IsBackground = true;
		thread.SetApartmentState(ApartmentState.STA);
		thread.Start();
	}

	private void SaveItemThread()
	{
		try
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
			if (saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				File.WriteAllText(saveFileDialog.FileName, testPanel.TextOutput);
			}
		}
		catch (Exception ex)
		{
			MessageBox.Show(string.Format(CommonResource.ErrMsgSaveFileFailed, ex.Source, ex.Message));
		}
	}

	public void unitDetectorOnChanged(bool connected, int portno)
	{
		UIHelper.InvokeOnUIifRequired(this, delegate
		{
			if (!testRunning)
			{
				if (runningRoundRobinExecution)
				{
					NotifyOfUnitDetectionForRoundRobin(connected);
				}
				else if (connected)
				{
					if (!uutConnected)
					{
						ActivatePanel(portno);
						uutConnected = true;
					}
				}
				else if (uutConnected)
				{
					DeActivatePanel();
					testPanel.UpdateStatus(TestPanel.PanelStatus.ConnectAUnit);
					uutConnected = false;
				}
			}
		});
	}

	public bool CreateUnitProgrammer(UnitProgrammerGenericSetup upgs, UnitProgrammerTechnicalSetup upts)
	{
		if (unitProgrammer != null && unitProgrammer.GenericSetup.Engine != upgs.Engine)
		{
			unitProgrammer.CloseUnitProgrammer();
			unitProgrammer.Dispose();
			unitProgrammer = null;
		}
		if (unitProgrammer == null)
		{
			if (upgs.Engine == "QSPRGUI")
			{
				unitProgrammer = new IUnitProgrammer(new QSPRGUIUnitProgrammer());
			}
			else
			{
				if (!(upgs.Engine == "QIA"))
				{
					MessageBox.Show("Unsupported Engine:" + upgs.Engine);
					return false;
				}
				unitProgrammer = new IUnitProgrammer(new QIAUnitProgrammer());
			}
			unitProgrammer.OnShown += unitProgrammer_OnShown;
			unitProgrammer.OnHidden += unitProgrammer_OnHidden;
			unitProgrammer.OnExited += unitProgrammer_OnExited;
			unitProgrammer.OnSetStatus += unitProgrammer_OnSetStatus;
			unitProgrammer.OnDisplayStatus += unitProgrammer_OnDisplayStatus;
			unitProgrammer.OnTestItemStarted += unitProgrammer_OnTestItemStarted;
			unitProgrammer.OnTestItemDone += unitProgrammer_OnTestItemDone;
			unitProgrammer.OnModifyTestTimeout += unitProgrammer_OnModifyTestTimeout;
			if (SNProvidedByEngine)
			{
				unitProgrammer.OnReceiveSN += unitProgrammer_OnReceiveSN;
			}
			IUnitProgrammer obj = unitProgrammer;
			obj.OnDone = (OnTestDone)Delegate.Combine(obj.OnDone, new OnTestDone(unitProgrammer_OnDone));
			unitProgrammer.GenericSetup.Engine = upgs.Engine;
		}
		unitProgrammer.GenericSetup.RunningRoundRobinExecution = upgs.RunningRoundRobinExecution;
		unitProgrammer.GenericSetup.SNProvidedByEngine = upgs.SNProvidedByEngine;
		unitProgrammer.GenericSetup.ShowStartStopMessages = upgs.ShowStartStopMessages;
		unitProgrammer.GenericSetup.DisplayDebugMessages = upgs.DisplayDebugMessages;
		unitProgrammer.GenericSetup.SaveMessagesToFile = upgs.SaveMessagesToFile;
		unitProgrammer.GenericSetup.StartAllTestServerAtInitialization = upgs.StartAllTestServerAtInitialization;
		unitProgrammer.GenericSetup.KillImmediatelyAfterTimeout = upgs.KillImmediatelyAfterTimeout;
		unitProgrammer.GenericSetup.ClassName = upgs.ClassName;
		unitProgrammer.GenericSetup.ModulePath = upgs.ModulePath;
		unitProgrammer.GenericSetup.ConfigurationString = upgs.ConfigurationString;
		unitProgrammer.GenericSetup.LogFilter = upgs.LogFilter;
		unitProgrammer.BackGroundColor = BackColor;
		unitProgrammer.Index = PanelNumber;
		unitProgrammer.TestPlanFilePath = upts.TestPlanFilePath.Trim('"');
		unitProgrammer.TestTimeoutSeconds = upts.TestTimeoutSeconds;
		unitProgrammer.TestTimeoutSecondsOffset = upts.TestTimeoutSecondsOffset;
		unitProgrammer.PanelSpecificGV = upts.PanelSpecificGV;
		unitProgrammer.TechnologySpecificGV = upts.TechnologySpecificGV;
		if (unitProgrammer.GenericSetup.StartAllTestServerAtInitialization && !unitProgrammer.IsProcessAlive)
		{
			unitProgrammer.StartUnitProgrammer();
		}
		return true;
	}

	public void ClearEvent()
	{
		this.OnZoomSelect = null;
		this.OnUnitConnected = null;
		this.OnExecutionCompleted = null;
		this.OnModifyTestTimeout = null;
	}

	public bool UnitProgrammerExists()
	{
		if (unitProgrammer != null)
		{
			return true;
		}
		return false;
	}

	private void unitProgrammer_OnDone(string serialNumber, TestResult testResult, string resultMessage)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				TestCompleted = true;
				if (testResult == TestResult.Passed)
				{
					testPanel.UpdateStatus(TestPanel.PanelStatus.Passed);
					panelStats.DeviceCompleted(PanelStat.TestResult.Passed);
				}
				else
				{
					if (testResult == TestResult.Failed)
					{
						string[] array = resultMessage.Split('\t');
						testPanel.AppendColorText("ErrorCode: ", Color.DarkRed);
						testPanel.AppendColorText(array[0] + "\n", Color.Red);
						testPanel.AppendColorText("SubErrorCode: ", Color.DarkRed);
						testPanel.AppendColorText(array[1] + "\n", Color.Red);
					}
					else if (testResult == TestResult.Exception)
					{
						string text = "Exception: " + resultMessage + "\n";
						testPanel.AppendColorText(text, Color.Black);
					}
					testPanel.UpdateStatus(TestPanel.PanelStatus.Failed);
					panelStats.DeviceCompleted(PanelStat.TestResult.Failed);
				}
				UpdateStats();
				TestRunning = false;
				if (unitProgrammer.GenericSetup.SaveMessagesToFile)
				{
					string text2 = "Log File => \"file://" + logFile + "\"\r\n";
					WriteLine(text2);
				}
				if (this.OnExecutionCompleted != null)
				{
					this.OnExecutionCompleted(this);
				}
			});
		}
		catch
		{
		}
	}

	private void unitProgrammer_OnReceiveSN(object sender, TextEventArgs e)
	{
		UIHelper.InvokeOnUIifRequired(this, delegate
		{
			string textSerialNumber = e.Text;
			if (SNProvidedByEngine)
			{
				testPanel.TextSerialNumber = textSerialNumber;
			}
		});
	}

	private void unitProgrammer_OnModifyTestTimeout(object obj, TextEventArgs e)
	{
		try
		{
			string text = e.Text;
			if (this.OnModifyTestTimeout != null && text.CompareTo(old_XttTimeout.ToString()) != 0)
			{
				this.OnModifyTestTimeout(text);
				old_XttTimeout = Convert.ToInt32(text);
			}
		}
		catch
		{
		}
	}

	private void unitProgrammer_OnSetStatus(object sender, TextEventArgs e)
	{
		UIHelper.InvokeOnUIifRequired(this, delegate
		{
			WriteLine(e.Text);
		});
	}

	private void unitProgrammer_OnReceiveNumTests(object sender, IntEventArgs e)
	{
		if (e.Data > 0)
		{
			testPanel.SetEstimatedNumberOfTests(e.Data);
		}
	}

	private void unitProgrammer_OnDisplayStatus(object sender, TextEventArgs e)
	{
		testPanel.TestCompleted();
		UIHelper.InvokeOnUIifRequired(this, delegate
		{
			DisplayStatus(e.Text);
		});
	}

	private void unitProgrammer_OnTestItemStarted(object sender, TextEventArgs e)
	{
		UIHelper.InvokeOnUIifRequired(this, delegate
		{
			TestItemStarted(e.Text);
		});
	}

	private void unitProgrammer_OnTestItemDone(object sender, TestResultEventArgs e)
	{
		UIHelper.InvokeOnUIifRequired(this, delegate
		{
			TestItemDone(e.TestName, e.TestResult);
		});
	}

	private void unitProgrammer_OnExited(object sender, EventArgs e)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				ContextMenuStrip.Items["Hide Unit Programmer"].Enabled = false;
				ContextMenuStrip.Items["Show Unit Programmer"].Enabled = false;
			});
		}
		catch
		{
		}
	}

	private void unitProgrammer_OnHidden(object sender, EventArgs e)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				ContextMenuStrip.Items["Show Unit Programmer"].Enabled = true;
				ContextMenuStrip.Items["Hide Unit Programmer"].Enabled = false;
			});
		}
		catch
		{
		}
	}

	private void unitProgrammer_OnShown(object sender, EventArgs e)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				ContextMenuStrip.Items["Show Unit Programmer"].Enabled = false;
				ContextMenuStrip.Items["Hide Unit Programmer"].Enabled = true;
			});
		}
		catch
		{
		}
	}

	private void hideQSPRItem_Click(object sender, EventArgs e)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				unitProgrammer.HideUnitProgrammer();
			});
		}
		catch
		{
		}
	}

	private void showQSPRItem_Click(object sender, EventArgs e)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				unitProgrammer.ShowUnitProgrammer();
			});
		}
		catch
		{
		}
	}

	private void ActivatePanel(int portno)
	{
		if (TestRunning)
		{
			StopBanner();
			return;
		}
		ReadOnly = false;
		testPanel.ClearPanel();
		ClearTestResults();
		if (detectionInstance == DetectionInstance.DETECT_INST_PHY_ADDR)
		{
			expectedCOMPortAtStart = portno;
			expectedCOMPortAfterPowerCycle = 0;
		}
		else if (expectedCOMPortAtStart != portno)
		{
			return;
		}
		unitProgrammer.SetPortNo(expectedCOMPortAtStart, expectedCOMPortAfterPowerCycle);
		if (!SNProvidedByEngine)
		{
			FocusSerialNumber();
		}
		else
		{
			StartProgrammingUnit("NA");
		}
	}

	private void DeActivatePanel()
	{
		if (testRunning)
		{
			StartBanner("!! DDT !!", Color.Red);
			return;
		}
		ReadOnly = true;
		TestRunning = false;
		EnableTabs();
		ClearTestResults();
	}

	public void ShowQspr()
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				unitProgrammer.ShowUnitProgrammer();
			});
		}
		catch
		{
		}
	}

	public void HideQspr()
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				unitProgrammer.HideUnitProgrammer();
			});
		}
		catch
		{
		}
	}

	public void ResetLastCompletionTime()
	{
		panelStats.ResetLastCompletionTime();
	}

	public void StartProgrammingUnit(string serialNumber)
	{
		if (!TestRunning)
		{
			StopBanner();
			if (panelStats.TimeElapsedSinceLastTest() > 6.0)
			{
				TestRunning = true;
				ReadOnly = true;
				logFile = Path.Combine(logFileDir, DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
				unitProgrammer.StartTestThread(serialNumber);
				DisableTabs();
				testPanel.UpdateStatus(TestPanel.PanelStatus.Running);
				panelStats.DeviceStartedExecution();
			}
			else
			{
				string text = $"Test started within {panelStats.TimeElapsedSinceLastTest()} seconds\r\nTest must start after at least {6} seconds.";
				text += "\r\nPlease disconnect and Connect the device in order to start the test.\r\n";
				testPanel.WriteLine(text);
			}
		}
	}

	private void UpdateStatusPanel(TestPanel.PanelStatus status)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				testPanel.UpdateStatus(status);
			});
		}
		catch
		{
		}
	}

	private void UpdateStatusPanelForQueuedRoundRobin(int queued)
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				string text = "Queued " + queued;
				testPanel.UpdateStatus(TestPanel.PanelStatus.Queued, text);
			});
		}
		catch
		{
		}
	}

	public void UpdateStatusPanelRoundRobin(int queued)
	{
		UpdateStatusPanelForQueuedRoundRobin(queued);
	}

	private void ActivatePanelRoundRobin()
	{
		try
		{
			UIHelper.InvokeOnUIifRequired(this, delegate
			{
				if (TestRunning)
				{
					StopBanner();
				}
				else
				{
					ReadOnly = false;
					testPanel.ClearPanel();
					ClearTestResults();
					if (!SNProvidedByEngine)
					{
						FocusSerialNumber();
					}
					else
					{
						StartProgrammingUnit("NA");
					}
				}
			});
		}
		catch
		{
		}
	}

	public bool StartExecutionForRoundRobin()
	{
		if (panelStats.TimeElapsedSinceLastTest() > 6.0)
		{
			ActivatePanelRoundRobin();
			return true;
		}
		UpdateStatusPanel(TestPanel.PanelStatus.ConnectAUnit);
		WriteLine($"Test started within {panelStats.TimeElapsedSinceLastTest()} seconds\r\nTest must start after at least 6 seconds.");
		WriteLine("\r\nPlease disconnect and Connect the device in order to start the test");
		return false;
	}

	public void NotifyOfUnitDetectionForRoundRobin(bool connected)
	{
		if (connected)
		{
			uutConnected = true;
			if (this.OnUnitConnected != null)
			{
				this.OnUnitConnected(this, connected);
			}
			return;
		}
		if (this.OnUnitConnected != null)
		{
			this.OnUnitConnected(this, connected);
		}
		uutConnected = false;
		DeActivatePanel();
		testPanel.UpdateStatus(TestPanel.PanelStatus.ConnectAUnit);
	}

	public void ResetStationYield()
	{
		panelStats.ResetStats();
		testPanel.ResetStats();
	}

	private void UpdateStats()
	{
		panelStats.GetTestTime(out var mins, out var secs);
		panelStats.GetTotalUpTime(out var hours, out var mins2);
		panelStats.GetAvgTestTime(out var mins3, out var secs2);
		panelStats.GetYieldStats(out var yield, out var passed, out var failed);
		testPanel.UpdateStats(yield, passed, failed, mins, secs, mins3, secs2, hours, mins2);
	}
}
