using System.Collections.Generic;
using System.IO.Ports;

namespace QC.QMSCT;

public class PortDiff
{
	private List<string> originalState = new List<string>();

	public PortDiff()
	{
		UpdateCurrentState();
	}

	public void UpdateCurrentState()
	{
		originalState.Clear();
		string[] portNames = SerialPort.GetPortNames();
		originalState.AddRange(portNames);
	}

	public bool WereDeviceAdded()
	{
		string[] portNames = SerialPort.GetPortNames();
		if (portNames.Length > originalState.Count)
		{
			return true;
		}
		return false;
	}

	public void GetDiffFromPreviousState(ref List<string> diff)
	{
		diff = new List<string>();
		diff.Clear();
		string[] portNames = SerialPort.GetPortNames();
		List<string> list = new List<string>();
		string[] array = portNames;
		foreach (string item in array)
		{
			list.Add(item);
		}
		foreach (string item2 in list)
		{
			if (!originalState.Contains(item2))
			{
				diff.Add(item2);
			}
		}
	}

	public void GetDiffFromPreviousStateInCommaDelimitedForm(out string diffPorts)
	{
		diffPorts = "";
		try
		{
			List<string> diff = null;
			string text = "";
			GetDiffFromPreviousState(ref diff);
			foreach (string item in diff)
			{
				text = item;
				text = text.Remove(0, 3);
				diffPorts += text;
				diffPorts += ",";
			}
			if (diffPorts.Length > 0 && diffPorts.LastIndexOf(',') == diffPorts.Length - 1)
			{
				diffPorts = diffPorts.Substring(0, diffPorts.Length - 1);
			}
		}
		catch
		{
		}
	}
}
