using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using DebugToolInstrumentInterface;

namespace QFDT_Components;

public partial class PowerSupply : UserControl, IComponentConnector
{
	public delegate void SendDebugMessage(MessageLevel level, string message);

	private delegate void UpdateCurrentCB(double current);

	public SendDebugMessage DebugMessageCB;

	public IPowerSupply ptrPs;

	private Thread measureCurrentThread;

	private volatile bool _stopCurrentThread;

	public void Register_DebugMessageCB(SendDebugMessage me)
	{
		DebugMessageCB = me;
	}

	public PowerSupply()
	{
		InitializeComponent();
		base.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
	}

	private void Dispatcher_ShutdownStarted(object sender, EventArgs e)
	{
		if (ptrPs != null)
		{
			_stopCurrentThread = true;
		}
	}

	private void On_Click(object sender, RoutedEventArgs e)
	{
		if (ptrPs != null)
		{
			ptrPs.TurnOnOff(OnOff: true);
			ptrPs.SetCurrentLimit(4.0);
			DebugMessageCB(MessageLevel.SUCCESS, "Turn Power Supply On ");
			measureCurrentThread = new Thread(MeasurecurrentThread);
			measureCurrentThread.Name = "Measure Current";
			_stopCurrentThread = false;
			measureCurrentThread.Start();
		}
	}

	private void MeasurecurrentThread()
	{
		if (ptrPs != null)
		{
			double num = 0.0;
			while (!_stopCurrentThread)
			{
				num = ptrPs.GetCurrent();
				UpdateCurrent(num);
				Thread.Sleep(100);
			}
		}
	}

	private void Off_Click(object sender, RoutedEventArgs e)
	{
		if (ptrPs != null)
		{
			ptrPs.TurnOnOff(OnOff: false);
			_stopCurrentThread = true;
			DebugMessageCB(MessageLevel.SUCCESS, "Turn Power Supply Off ");
		}
	}

	private void Measure_Click(object sender, RoutedEventArgs e)
	{
		if (ptrPs != null)
		{
			txtCurrent.Text = ptrPs.GetCurrent().ToString();
		}
	}

	private void Voltage_Click(object sender, RoutedEventArgs e)
	{
		if (ptrPs != null)
		{
			ptrPs.SetVoltage(Convert.ToDouble(txtVolt.Text.ToString()));
			DebugMessageCB(MessageLevel.SUCCESS, "Set Voltage " + txtVolt.Text.ToString());
		}
	}

	public void UpdateCurrent(double current)
	{
		if (txtCurrent.Dispatcher.CheckAccess())
		{
			txtCurrent.Text = $"{current:0.###}";
			return;
		}
		UpdateCurrentCB method = UpdateCurrent;
		base.Dispatcher.BeginInvoke(method, current);
	}

	private void On_Unloaded(object sender, RoutedEventArgs e)
	{
	}
}
