using System;
using System.IO;
using System.Reflection;
using QC.MCI;

namespace QC.MultiplexManager;

public class MuxCfg
{
	private Multiplexer mux;

	private int path = -1;

	private string port = "";

	private MultiplexControlInterface mci;

	public Multiplexer Mux
	{
		get
		{
			return mux;
		}
		set
		{
			mux = value;
		}
	}

	public int Path
	{
		get
		{
			return path;
		}
		set
		{
			path = value;
		}
	}

	public string Port
	{
		get
		{
			return port;
		}
		set
		{
			port = value;
		}
	}

	public MultiplexControlInterface MuxCtrlInterface
	{
		get
		{
			if (mci == null)
			{
				FileInfo fileInfo = new FileInfo(Mux.DriverDLL);
				if (!fileInfo.Exists)
				{
					string directoryName = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
					fileInfo = new FileInfo(System.IO.Path.Combine(directoryName, Mux.DriverDLL));
				}
				if (!fileInfo.Exists)
				{
					throw new Exception(Mux.DriverDLL + " does not exist!");
				}
				Assembly assembly = Assembly.LoadFrom(fileInfo.FullName);
				Type typeFromHandle = typeof(MultiplexControlInterface);
				Type[] types = assembly.GetTypes();
				foreach (Type type in types)
				{
					if (type.BaseType.FullName == typeFromHandle.FullName)
					{
						mci = Activator.CreateInstance(type) as MultiplexControlInterface;
						break;
					}
				}
				if (mci == null)
				{
					throw new Exception("Unable to create instance of MultiplexControlInterface for DRIVER_DLL: " + Mux.DriverDLL);
				}
			}
			mci.BusConfiguration = Mux.BusConfig;
			if (Mux.SimulationMode.ToUpper().Contains("YES"))
			{
				mci.SimulationMode = true;
			}
			else
			{
				mci.SimulationMode = false;
			}
			if (!mci.Configure())
			{
				return mci = null;
			}
			return mci;
		}
	}
}
