using System.Management;

namespace QC.QMSCT;

public class USBPortNotification
{
	public delegate void DeviceConnectionChangeDetected(bool connected, string portDiff);

	private PortDiff detectPortDiff = new PortDiff();

	private ManagementEventWatcher watcher;

	private WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent");

	public event DeviceConnectionChangeDetected OnDeviceConnectionChange;

	public void Stop()
	{
		try
		{
			if (watcher != null)
			{
				watcher.Stop();
			}
		}
		catch
		{
		}
	}

	public void Start()
	{
		detectPortDiff.UpdateCurrentState();
		if (watcher == null)
		{
			watcher = new ManagementEventWatcher(query);
			watcher.EventArrived += watcher_EventArrived;
		}
		watcher.Start();
	}

	private void watcher_EventArrived(object sender, EventArrivedEventArgs e)
	{
		if (detectPortDiff.WereDeviceAdded())
		{
			if (this.OnDeviceConnectionChange != null)
			{
				string diffPorts = "";
				detectPortDiff.GetDiffFromPreviousStateInCommaDelimitedForm(out diffPorts);
				this.OnDeviceConnectionChange(connected: true, diffPorts);
			}
		}
		else
		{
			detectPortDiff.UpdateCurrentState();
		}
	}
}
