using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml.Serialization;
using MultiLanguageManger;

namespace QC.QMSCT;

public class StationConfiguration
{
	public delegate void LoadEvent();

	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct StationConfigDefaultValues
	{
		public const int NUMBER_OF_PANELS = 8;

		public const int NUMBER_OF_COLUMNS = 4;

		public const bool START_QSPR_AT_SETUP = false;

		public const bool USE_USB_SIMULATOR = false;

		public const string APP_LANGUAGE = "ENGLISH";

		public const bool ROUND_ROBIN_SCHEDULING = false;

		public const bool SHOW_DEBUGMESSAGES_FROM_ENGINE = true;

		public const bool SHOW_SAME_COLOR = false;

		public const bool GET_SN_FROM_ENGINE = true;

		public const int VIDPID = 10;
	}

	public const int MAX_PANELS = 16;

	public const int MAX_COLUMNS = 8;

	public const int Default1stPort = 50;

	public const int Default2ndPort = 100;

	public const string DefaultHwAddr = "PCIROOT";

	private StationConfigSetup stationconfig;

	private string filename;

	public LoadEvent OnLoad;

	public string Filename
	{
		get
		{
			return filename;
		}
		set
		{
			filename = value;
		}
	}

	public string StationName
	{
		get
		{
			return stationconfig.StationName;
		}
		set
		{
			stationconfig.StationName = value;
		}
	}

	public int NumberOfPanels
	{
		get
		{
			return Convert.ToInt32(stationconfig.NumberOfPanels);
		}
		set
		{
			stationconfig.NumberOfPanels = Convert.ToString(value);
		}
	}

	public int NumberOfColumns
	{
		get
		{
			return Convert.ToInt32(stationconfig.NumberOfColumns);
		}
		set
		{
			stationconfig.NumberOfColumns = Convert.ToString(value);
		}
	}

	public string AppLanguage
	{
		get
		{
			return stationconfig.AppLanguage;
		}
		set
		{
			stationconfig.AppLanguage = value;
		}
	}

	public bool KillEngineImmediatelyAfterTimeout
	{
		get
		{
			return stationconfig.KillEngineImmediatelyAfterTimeout;
		}
		set
		{
			stationconfig.KillEngineImmediatelyAfterTimeout = value;
		}
	}

	public bool ShowDebugMessagesFromEngine
	{
		get
		{
			return stationconfig.ShowDebugMessagesFromEngine;
		}
		set
		{
			stationconfig.ShowDebugMessagesFromEngine = value;
		}
	}

	public bool SaveMessagesToFile
	{
		get
		{
			return stationconfig.SaveMessagesToFile;
		}
		set
		{
			stationconfig.SaveMessagesToFile = value;
		}
	}

	public bool ShowEngineStartStopMessages
	{
		get
		{
			return stationconfig.ShowEngineStartStopMessages;
		}
		set
		{
			stationconfig.ShowEngineStartStopMessages = value;
		}
	}

	public bool ShowSameColor
	{
		get
		{
			return stationconfig.ShowSameColor;
		}
		set
		{
			stationconfig.ShowSameColor = value;
		}
	}

	public bool GetSNFromEngine
	{
		get
		{
			return stationconfig.GetSNFromEngine;
		}
		set
		{
			stationconfig.GetSNFromEngine = value;
		}
	}

	public bool UseUSBSimulator
	{
		get
		{
			return stationconfig.UseUSBSimulator;
		}
		set
		{
			stationconfig.UseUSBSimulator = value;
		}
	}

	public PortMapType[] PortMapping
	{
		get
		{
			return stationconfig.Setup.PortMapping;
		}
		set
		{
			stationconfig.Setup.PortMapping = value;
		}
	}

	public DetectionInstance DetectionInstanceValue
	{
		get
		{
			if (stationconfig.Setup.DetectionInstanceValue == DetectionInstance.DETECT_INST_NET_MODE.ToString())
			{
				return DetectionInstance.DETECT_INST_NET_MODE;
			}
			if (stationconfig.Setup.DetectionInstanceValue == DetectionInstance.DETECT_INST_PORT_NO.ToString())
			{
				return DetectionInstance.DETECT_INST_PORT_NO;
			}
			return DetectionInstance.DETECT_INST_PHY_ADDR;
		}
		set
		{
			stationconfig.Setup.DetectionInstanceValue = value.ToString();
		}
	}

	public bool DualPortSolution
	{
		get
		{
			return stationconfig.Setup.DualPortSolution;
		}
		set
		{
			stationconfig.Setup.DualPortSolution = value;
		}
	}

	public bool ManualSetup
	{
		get
		{
			return stationconfig.Setup.ManualSetup;
		}
		set
		{
			stationconfig.Setup.ManualSetup = value;
		}
	}

	public bool RunRoundRobinScheduling
	{
		get
		{
			return stationconfig.Options.Scheduling.RunRoundRobinScheduling;
		}
		set
		{
			stationconfig.Options.Scheduling.RunRoundRobinScheduling = value;
		}
	}

	public bool StartQSPRAtStartofQMSCT
	{
		get
		{
			return stationconfig.Options.Scheduling.StartQSPRAtStartOnSetup;
		}
		set
		{
			stationconfig.Options.Scheduling.StartQSPRAtStartOnSetup = value;
		}
	}

	public VidPidType[] VidPids
	{
		get
		{
			return stationconfig.Options.UsbSetup;
		}
		set
		{
			stationconfig.Options.UsbSetup = value;
		}
	}

	public MessageFilterSetup MessageFilter
	{
		get
		{
			return stationconfig.MessageFilter;
		}
		set
		{
			stationconfig.MessageFilter = value;
		}
	}

	public string[] LogCategories
	{
		get
		{
			return stationconfig.MessageFilter.LogCategories;
		}
		set
		{
			stationconfig.MessageFilter.LogCategories = value;
		}
	}

	public StationConfiguration()
	{
		stationconfig = new StationConfigSetup();
		stationconfig.Setup = new StationSetup();
		stationconfig.Options = new OptionSetup();
		stationconfig.Options.UsbSetup = new VidPidType[1];
		stationconfig.Options.Scheduling = new SchedulingSetup();
		stationconfig.Setup = new StationSetup();
		stationconfig.MessageFilter = new MessageFilterSetup();
	}

	public StationConfiguration(string filename)
		: this()
	{
		Load(filename);
	}

	public void Load(string filename)
	{
		if (!File.Exists(filename))
		{
			throw new Exception(filename + " not exists!!");
		}
		FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
		try
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(StationConfigSetup));
			stationconfig = (StationConfigSetup)xmlSerializer.Deserialize(fileStream);
			if (stationconfig.MessageFilter == null)
			{
				stationconfig.MessageFilter = new MessageFilterSetup();
			}
			int num = 0;
			PortMapType[] portMapping = stationconfig.Setup.PortMapping;
			foreach (PortMapType portMapType in portMapping)
			{
				if (portMapType.PortData == null)
				{
					portMapType.PortData = new PortDataType();
				}
				if (portMapType.PortData.USBPhysicalAddress != null && !(portMapType.PortData.USBPhysicalAddress == ""))
				{
					continue;
				}
				string text = "PCIROOT(0)";
				bool flag = true;
				while (flag)
				{
					flag = false;
					text = "PCIROOT(" + num + ")";
					PortMapType[] portMapping2 = stationconfig.Setup.PortMapping;
					foreach (PortMapType portMapType2 in portMapping2)
					{
						if (portMapType2.PortData.USBPhysicalAddress == text)
						{
							flag = true;
						}
					}
					if (flag)
					{
						num++;
					}
				}
				portMapType.PortData.USBPhysicalAddress = text;
			}
			fileStream.Close();
			this.filename = filename;
			LoadVerifyStationProductConfigurations();
			StationName = Path.GetFileNameWithoutExtension(filename);
			if (OnLoad != null)
			{
				OnLoad();
			}
		}
		catch (Exception ex)
		{
			throw new Exception("Unable to read station configuration file. " + filename + " Exception: " + ex.Message);
		}
		finally
		{
			fileStream.Close();
		}
	}

	private void LoadVerifyStationProductConfigurations()
	{
		try
		{
			if (NumberOfPanels < 1 || NumberOfPanels > 16)
			{
				MessageBox.Show(CommonResource.BoxMsgPanelOverrange);
				NumberOfPanels = 8;
			}
			if (NumberOfColumns < 1 || NumberOfColumns > 6)
			{
				MessageBox.Show(CommonResource.BoxMsgColOverrange);
				NumberOfColumns = 4;
			}
			if (NumberOfPanels > PortMapping.Length)
			{
				string text = string.Format(CommonResource.BoxMsgDisplayedPanelWarning, stationconfig.NumberOfPanels.ToString(), PortMapping.Length.ToString(), PortMapping.Length.ToString());
				NumberOfPanels = PortMapping.Length;
				MessageBox.Show(text, CommonResource.BoxTitleDisplayedPanelWarning);
			}
			List<int> list = new List<int>();
			List<string> list2 = new List<string>();
			PortMapType[] portMapping = PortMapping;
			foreach (PortMapType portMapType in portMapping)
			{
				if (DetectionInstanceValue == DetectionInstance.DETECT_INST_PORT_NO && list.Contains(portMapType.PortData.COMPortAtStart) && portMapType.PortData.COMPortAtStart != 0)
				{
					throw new Exception(string.Format(CommonResource.ErrMsgDuplicatedPortFound, portMapType.PortData.COMPortAtStart));
				}
				if (DetectionInstanceValue == DetectionInstance.DETECT_INST_PHY_ADDR && list2.Contains(portMapType.PortData.USBPhysicalAddress) && portMapType.PortData.USBPhysicalAddress != "PCIROOT(0)")
				{
					throw new Exception(string.Format(CommonResource.ErrMsgDuplicatedPortFound, portMapType.PortData.USBPhysicalAddress));
				}
				list.Add(portMapType.PortData.COMPortAtStart);
				list2.Add(portMapType.PortData.USBPhysicalAddress);
			}
			if (stationconfig.AppLanguage == null)
			{
				stationconfig.AppLanguage = "English";
			}
			Save();
		}
		catch (Exception ex)
		{
			throw new Exception(string.Format(CommonResource.ErrMsgLoadConfigFileFailed, filename, ex.Source, ex.Message));
		}
	}

	public void CreateDefaultStationConfigSetupXml(string filename)
	{
		try
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(StationConfigSetup));
			stationconfig.NumberOfPanels = 8.ToString();
			stationconfig.NumberOfColumns = 4.ToString();
			stationconfig.AppLanguage = "ENGLISH";
			stationconfig.ShowSameColor = false;
			stationconfig.KillEngineImmediatelyAfterTimeout = true;
			stationconfig.ShowEngineStartStopMessages = false;
			stationconfig.ShowDebugMessagesFromEngine = true;
			stationconfig.GetSNFromEngine = true;
			stationconfig.Options.Scheduling.RunRoundRobinScheduling = false;
			stationconfig.Options.Scheduling.StartQSPRAtStartOnSetup = false;
			stationconfig.Setup.DetectionInstanceValue = DetectionInstance.DETECT_INST_PORT_NO.ToString();
			stationconfig.Setup.ManualSetup = true;
			stationconfig.Setup.DualPortSolution = false;
			stationconfig.Setup.PortMapping = new PortMapType[8];
			stationconfig.Options.UsbSetup = new VidPidType[10];
			for (int i = 0; i < VidPids.Length; i++)
			{
				stationconfig.Options.UsbSetup[i] = new VidPidType();
				stationconfig.Options.UsbSetup[i].VID = "05C6";
				switch (i)
				{
				case 0:
					stationconfig.Options.UsbSetup[i].PID = "9006";
					break;
				case 1:
					stationconfig.Options.UsbSetup[i].PID = "9008";
					break;
				case 2:
					stationconfig.Options.UsbSetup[i].PID = "9025";
					break;
				case 3:
					stationconfig.Options.UsbSetup[i].PID = "9026";
					break;
				case 4:
					stationconfig.Options.UsbSetup[i].PID = "9031";
					break;
				case 5:
					stationconfig.Options.UsbSetup[i].PID = "9032";
					break;
				case 6:
					stationconfig.Options.UsbSetup[i].PID = "9037";
					break;
				case 7:
					stationconfig.Options.UsbSetup[i].PID = "9038";
					break;
				case 8:
					stationconfig.Options.UsbSetup[i].PID = "9053";
					break;
				case 9:
					stationconfig.Options.UsbSetup[i].PID = "9091";
					break;
				}
				stationconfig.Options.UsbSetup[i].Ignore = true;
			}
			for (int j = 0; j < NumberOfPanels; j++)
			{
				stationconfig.Setup.PortMapping[j] = new PortMapType();
				stationconfig.Setup.PortMapping[j].PanelNumber = j + 1;
				stationconfig.Setup.PortMapping[j].PortData = new PortDataType();
				stationconfig.Setup.PortMapping[j].PortData.COMPortAtStart = 50 + stationconfig.Setup.PortMapping[j].PanelNumber;
				stationconfig.Setup.PortMapping[j].PortData.COMPortAfterPowerCycle = 100 + stationconfig.Setup.PortMapping[j].PanelNumber;
				stationconfig.Setup.PortMapping[j].PortData.USBPhysicalAddress = "PCIROOT(" + stationconfig.Setup.PortMapping[j].PanelNumber + ")";
				stationconfig.Setup.PortMapping[j].PortData.PanelSpecificGV = "";
			}
			StreamWriter streamWriter = new StreamWriter(File.Create(filename));
			xmlSerializer.Serialize(streamWriter, stationconfig);
			streamWriter.Close();
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message);
		}
	}

	public void Save(string filename = null)
	{
		if (filename == null)
		{
			filename = this.filename;
		}
		StationName = Path.GetFileNameWithoutExtension(filename);
		FileStream fileStream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
		try
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(StationConfigSetup));
			xmlSerializer.Serialize(fileStream, stationconfig);
			this.filename = filename;
		}
		catch (Exception ex)
		{
			throw new Exception("Unable to save station configuration file. " + filename + "Exception: " + ex.Message);
		}
		finally
		{
			fileStream.Close();
		}
	}

	public List<string> GetLogFilter()
	{
		try
		{
			List<string> list = new List<string>();
			if (LogCategories != null)
			{
				string[] logCategories = LogCategories;
				foreach (string item in logCategories)
				{
					list.Add(item);
				}
			}
			return list;
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message);
			return null;
		}
	}
}
