using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.Serialization;
using ProductConfigurationController;

namespace QC.QMSCT;

public class QmsctSettings
{
	public const string ConfigRootFolderDefault = "C:\\Qualcomm\\QMSCT\\configuration";

	private ProductConfigManager productConfigManager = new ProductConfigManager();

	private StationConfiguration stationConfiguration = new StationConfiguration();

	private PortDetectionSettings portDetectionSettings = new PortDetectionSettings();

	private QMSCTSetup qmsctSetup;

	private string productname;

	private string productconfig;

	private string filename = "C:\\Qualcomm\\QMSCT\\QMSCTSetup.xml";

	private string configname = "C:\\Qualcomm\\QMSCT\\configuration\\QMSCT.config";

	public ProductConfigManager ProductConfigManager => productConfigManager;

	public StationConfiguration StationConfiguration => stationConfiguration;

	public PortDetectionSettings PortDetectionSettings => portDetectionSettings;

	public UnitProgrammerGenericSetup UnitProgrammerGenericSetup => GetUnitProgrammerGenericSetup();

	public string ConfigRootFolder => qmsctSetup.RootFolder;

	public string ProductName
	{
		get
		{
			return productname;
		}
		set
		{
			productname = value;
		}
	}

	public string ProductConfig
	{
		get
		{
			return productconfig;
		}
		set
		{
			productconfig = value;
		}
	}

	public string[] RougeProcess => qmsctSetup.RougeProcess;

	public bool EnableAllDoneProcess
	{
		get
		{
			if (qmsctSetup.AllDoneProcessSpecified)
			{
				return qmsctSetup.AllDoneProcess;
			}
			return false;
		}
	}

	private void WarningMessage(string Message, string Title)
	{
		MessageBox.Show(Message, Title);
	}

	public QmsctSettings()
	{
		ProductConfigManager obj = productConfigManager;
		obj.WarningDialog = (WarningCallcack)Delegate.Combine(obj.WarningDialog, new WarningCallcack(WarningMessage));
	}

	public UnitProgrammerTechnicalSetup GetUnitProgrammerTechnicalSetup(int PanelIndex)
	{
		UnitProgrammerTechnicalSetup unitProgrammerTechnicalSetup = new UnitProgrammerTechnicalSetup();
		unitProgrammerTechnicalSetup.TestPlanFilePath = productConfigManager.TestPlanFilePath.Trim('"');
		unitProgrammerTechnicalSetup.TestTimeoutSeconds = productConfigManager.TestTimeoutSeconds;
		unitProgrammerTechnicalSetup.TestTimeoutSecondsOffset = productConfigManager.TestTimeoutSecondsOffset;
		PortMapType[] portMapping = stationConfiguration.PortMapping;
		foreach (PortMapType portMapType in portMapping)
		{
			if (portMapType.PanelNumber == PanelIndex)
			{
				unitProgrammerTechnicalSetup.PanelSpecificGV = portMapType.PortData.PanelSpecificGV;
			}
		}
		unitProgrammerTechnicalSetup.TechnologySpecificGV = productConfigManager.TechnologySpecificGV;
		return unitProgrammerTechnicalSetup;
	}

	private UnitProgrammerGenericSetup GetUnitProgrammerGenericSetup()
	{
		UnitProgrammerGenericSetup unitProgrammerGenericSetup = new UnitProgrammerGenericSetup();
		unitProgrammerGenericSetup.RunningRoundRobinExecution = stationConfiguration.RunRoundRobinScheduling;
		unitProgrammerGenericSetup.SNProvidedByEngine = stationConfiguration.GetSNFromEngine;
		unitProgrammerGenericSetup.ShowStartStopMessages = stationConfiguration.ShowEngineStartStopMessages;
		unitProgrammerGenericSetup.DisplayDebugMessages = stationConfiguration.ShowDebugMessagesFromEngine;
		unitProgrammerGenericSetup.SaveMessagesToFile = stationConfiguration.SaveMessagesToFile;
		unitProgrammerGenericSetup.StartAllTestServerAtInitialization = stationConfiguration.StartQSPRAtStartofQMSCT;
		unitProgrammerGenericSetup.KillImmediatelyAfterTimeout = stationConfiguration.KillEngineImmediatelyAfterTimeout;
		if (stationConfiguration.LogCategories == null)
		{
			unitProgrammerGenericSetup.LogFilter = new List<string>();
		}
		else
		{
			unitProgrammerGenericSetup.LogFilter = stationConfiguration.LogCategories.ToList();
		}
		unitProgrammerGenericSetup.Engine = productConfigManager.Engine;
		SupportedEngineType[] engineSetup = qmsctSetup.EngineSetup;
		foreach (SupportedEngineType supportedEngineType in engineSetup)
		{
			if (productConfigManager.Engine == supportedEngineType.Name)
			{
				unitProgrammerGenericSetup.ClassName = supportedEngineType.ClassName;
				unitProgrammerGenericSetup.ModulePath = supportedEngineType.ModulePath;
				unitProgrammerGenericSetup.ConfigurationString = supportedEngineType.EngineConfigurationString;
				break;
			}
		}
		return unitProgrammerGenericSetup;
	}

	public bool Load()
	{
		FileStream fileStream = null;
		try
		{
			if (!File.Exists(filename))
			{
				throw new Exception(filename + " not exists!!");
			}
			fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(QMSCTSetup));
			qmsctSetup = (QMSCTSetup)xmlSerializer.Deserialize(fileStream);
			fileStream.Close();
			ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
			exeConfigurationFileMap.ExeConfigFilename = configname;
			Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
			new List<string>();
			string[] allKeys = configuration.AppSettings.Settings.AllKeys;
			foreach (string text in allKeys)
			{
				if (text == "ProductName")
				{
					productname = configuration.AppSettings.Settings[text].Value;
				}
				if (text == "ProductConfig")
				{
					productconfig = configuration.AppSettings.Settings[text].Value;
				}
			}
			VerifyQMSCTSetup();
			return true;
		}
		catch (Exception ex)
		{
			WarningMessage("Unable to read QMSCT configuration file. " + filename + " Exception: " + ex.Message, "Error");
			fileStream?.Close();
			return false;
		}
	}

	private void Save()
	{
		FileStream fileStream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
		try
		{
			qmsctSetup.PortDetectionSetting = portDetectionSettings.QmsctSetupPortDetectionSetting;
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(QMSCTSetup));
			xmlSerializer.Serialize(fileStream, qmsctSetup);
		}
		catch (Exception ex)
		{
			throw new Exception("Unable to save station configuration file. " + filename + "Exception: " + ex.Message);
		}
		finally
		{
			fileStream.Close();
		}
	}

	private void ModifySetting(Configuration config, string name, string value)
	{
		config.AppSettings.Settings.Remove(name);
		config.AppSettings.Settings.Add(name, value);
	}

	public void SaveAppConfiguration()
	{
		ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
		exeConfigurationFileMap.ExeConfigFilename = configname;
		Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
		ModifySetting(configuration, "ProductName", productname);
		ModifySetting(configuration, "ProductConfig", productconfig);
		configuration.Save(ConfigurationSaveMode.Modified);
		ConfigurationManager.RefreshSection("appSettings");
	}

	private void VerifyQMSCTSetup()
	{
		try
		{
			if (productname == null || productname == "")
			{
				productname = "8x26";
			}
			if (productconfig == null || productconfig == "")
			{
				productconfig = "Software Download";
			}
			if (qmsctSetup.RootFolder == null || qmsctSetup.RootFolder == "")
			{
				qmsctSetup.RootFolder = "C:\\Qualcomm\\QMSCT\\configuration";
			}
			if (qmsctSetup.PortDetectionSetting.DriverString.EDownloaderKey != null && qmsctSetup.PortDetectionSetting.DriverString.EDownloaderKey != "")
			{
				portDetectionSettings.QmsctSetupPortDetectionSetting.DriverString.EDownloaderKey = qmsctSetup.PortDetectionSetting.DriverString.EDownloaderKey;
			}
			if (qmsctSetup.PortDetectionSetting.DriverString.DiagnosticKey != null && qmsctSetup.PortDetectionSetting.DriverString.DiagnosticKey != "")
			{
				portDetectionSettings.QmsctSetupPortDetectionSetting.DriverString.DiagnosticKey = qmsctSetup.PortDetectionSetting.DriverString.DiagnosticKey;
			}
			if (qmsctSetup.PortDetectionSetting.DriverString.CustomizedKey != null && qmsctSetup.PortDetectionSetting.DriverString.CustomizedKey != "")
			{
				portDetectionSettings.QmsctSetupPortDetectionSetting.DriverString.CustomizedKey = qmsctSetup.PortDetectionSetting.DriverString.CustomizedKey;
			}
			portDetectionSettings.PortConnectionTimeoutInSec = qmsctSetup.PortDetectionSetting.PortConnectionTimeoutInSec;
			portDetectionSettings.DeviceManagerStabilizationTimeout = qmsctSetup.PortDetectionSetting.DeviceManagerStablizationTimeoutInSec;
			SupportedEngineType[] engineSetup = qmsctSetup.EngineSetup;
			foreach (SupportedEngineType supportedEngineType in engineSetup)
			{
				if (!(supportedEngineType.ModulePath != "") || !File.Exists(supportedEngineType.ModulePath))
				{
					continue;
				}
				Type[] types = Assembly.LoadFrom(supportedEngineType.ModulePath).GetTypes();
				foreach (Type type in types)
				{
					if (!(type.Name == supportedEngineType.ClassName))
					{
						continue;
					}
					MethodInfo method = type.GetMethod("ValidateEngineEnvironment");
					if (method != null && !method.IsStatic)
					{
						IDisposable disposable = Activator.CreateInstance(type) as IDisposable;
						if (Convert.ToBoolean(method.Invoke(disposable, null)))
						{
							productConfigManager.AddSupportedEngine(supportedEngineType.Name);
						}
						disposable.Dispose();
					}
				}
			}
			if (productConfigManager.EngineList.Count() == 0)
			{
				throw new Exception("No supported engine found.");
			}
			SupportedTecnnologyType[] technologySetup = qmsctSetup.TechnologySetup;
			foreach (SupportedTecnnologyType supportedTecnnologyType in technologySetup)
			{
				if (!(supportedTecnnologyType.ModulePath != "") || !File.Exists(supportedTecnnologyType.ModulePath))
				{
					continue;
				}
				if (supportedTecnnologyType.ModulePath.ToUpper() == "QMSCT.EXE")
				{
					Type[] types2 = Assembly.GetExecutingAssembly().GetTypes();
					foreach (Type type2 in types2)
					{
						if (type2.Name == supportedTecnnologyType.ClassName)
						{
							productConfigManager.AddSupportedTechnology(new KeyValuePair<string, List<string>>(supportedTecnnologyType.Name, supportedTecnnologyType.SupportedEngine.ToList()));
						}
					}
					continue;
				}
				Type[] types3 = Assembly.LoadFrom(supportedTecnnologyType.ModulePath).GetTypes();
				foreach (Type type3 in types3)
				{
					if (type3.Name == supportedTecnnologyType.ClassName)
					{
						productConfigManager.AddSupportedTechnology(new KeyValuePair<string, List<string>>(supportedTecnnologyType.Name, supportedTecnnologyType.SupportedEngine.ToList()));
					}
				}
			}
			if (productConfigManager.TechnologyList.Count() == 0)
			{
				throw new Exception("No supported technology found.");
			}
		}
		catch (Exception ex)
		{
			throw new Exception(ex.Message);
		}
	}

	public void CreateDefaultFile()
	{
		string text = ((!Environment.Is64BitOperatingSystem) ? "C:\\Program Files\\Qualcomm\\QDART\\bin" : "C:\\Program Files (x86)\\Qualcomm\\QDART\\bin");
		qmsctSetup = new QMSCTSetup();
		qmsctSetup.RootFolder = "C:\\Qualcomm\\QMSCT\\configuration";
		qmsctSetup.PortDetectionSetting = portDetectionSettings.QmsctSetupPortDetectionSetting;
		List<string> list = new List<string>();
		list.Add("qspr");
		list.Add("fh_loader");
		list.Add("qsaharaserver");
		qmsctSetup.RougeProcess = list.ToArray();
		qmsctSetup.AllDoneProcessSpecified = true;
		qmsctSetup.AllDoneProcess = false;
		List<SupportedEngineType> list2 = new List<SupportedEngineType>();
		SupportedEngineType supportedEngineType = new SupportedEngineType();
		supportedEngineType.Name = "QSPRGUI";
		supportedEngineType.ClassName = "QSPRGUIUnitProgrammer";
		supportedEngineType.ModulePath = "configPanel.dll";
		supportedEngineType.EngineConfigurationString = text + "\\QSPR.exe;1500";
		list2.Add(supportedEngineType);
		SupportedEngineType supportedEngineType2 = new SupportedEngineType();
		supportedEngineType2.Name = "QIA";
		supportedEngineType2.ClassName = "QIAUnitProgrammer";
		supportedEngineType2.ModulePath = "configPanel.dll";
		list2.Add(supportedEngineType2);
		qmsctSetup.EngineSetup = list2.ToArray();
		List<SupportedTecnnologyType> list3 = new List<SupportedTecnnologyType>();
		SupportedTecnnologyType supportedTecnnologyType = new SupportedTecnnologyType();
		supportedTecnnologyType.Name = "SWDL";
		supportedTecnnologyType.ModulePath = "QMSCT.exe";
		supportedTecnnologyType.ClassName = "MULTIDUT_SWDL";
		List<string> list4 = new List<string>();
		list4.Add("QSPRGUI");
		list4.Add("QIA");
		supportedTecnnologyType.SupportedEngine = list4.ToArray();
		list3.Add(supportedTecnnologyType);
		SupportedTecnnologyType supportedTecnnologyType2 = new SupportedTecnnologyType();
		supportedTecnnologyType2.Name = "MULTIDUT_RF";
		supportedTecnnologyType2.ModulePath = "QMSCT.exe";
		supportedTecnnologyType2.ClassName = "MULTIDUT_RF";
		list4.Clear();
		list4.Add("QSPRGUI");
		supportedTecnnologyType2.SupportedEngine = list4.ToArray();
		list3.Add(supportedTecnnologyType2);
		SupportedTecnnologyType supportedTecnnologyType3 = new SupportedTecnnologyType();
		supportedTecnnologyType3.Name = "MULTIDUT_MMI";
		supportedTecnnologyType3.ModulePath = "QMSCT.exe";
		supportedTecnnologyType3.ClassName = "MULTIDUT_MMI";
		list4.Clear();
		list4.Add("QSPRGUI");
		list4.Add("QIA");
		supportedTecnnologyType3.SupportedEngine = list4.ToArray();
		list3.Add(supportedTecnnologyType3);
		qmsctSetup.TechnologySetup = list3.ToArray();
		Save();
	}
}
