using System;
using System.IO;
using System.Security;
using System.Windows.Forms;
using System.Xml.Serialization;
using QC.QsprShared.Config;
using QC.QsprShared.Dialogs;
using QC.QsprShared.GlobalData;
using QC.QsprShared.Trace;
using QC.QTMApplication.Plugin.Common;
using QC.QTMInterface;

namespace QC.QTMApplication;

public class QSPRMain
{
	[STAThread]
	public static int Main(string[] args)
	{
		try
		{
			TraceMessage.StartXMLLogging();
			bool flag = false;
			CustomExceptionHandler @object = new CustomExceptionHandler();
			System.Windows.Forms.Application.ThreadException += @object.OnUIThreadException;
			AppDomain.CurrentDomain.UnhandledException += @object.OnThreadException;
			WorkspaceConfig WConfig = new WorkspaceConfig();
			QTMArguments qTMArguments = new QTMArguments();
			if (!qTMArguments.Parse(args))
			{
				qTMArguments.Usage();
				return -2;
			}
			TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp.Main", "FeatureConfigInfo.ExportToStruct();", TraceMessageType.Trace);
			GlobalInformation.RunTimeConfig = QSPRMainWindow.FeatureConfigInfo.ExportToStruct();
			TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp.Main", "LoadWConfig()", TraceMessageType.Trace);
			if (!LoadWConfig(out WConfig))
			{
				flag = true;
			}
			if (flag)
			{
				AppMessageDialog.Show("Loading Workspace config failed. QSPR is using the defaults. Please re do the workspace changes from 'Options\\EditConfigurations'.", "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.Error);
			}
			TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp.Main", "QSPR Arguments " + string.Join(" ", args), TraceMessageType.Trace);
			TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp.Main", "Automation mode set to " + GlobalStatus.AutomationMode, TraceMessageType.Trace);
			Analytics.SetupAnalytics();
			if (!WConfig.SuppressSpashScreen && qTMArguments.ShowSplashScreen)
			{
				SplashScreen_External splashScreen_External = new SplashScreen_External();
				splashScreen_External.ShowSplash();
			}
			else
			{
				SplashScreen.ShowSplashScreen(showScreen: false);
			}
			InitPluginDirectories();
			QSPRApp qSPRApp = new QSPRApp();
			qSPRApp.QtmArguments = qTMArguments;
			qSPRApp.WConfig = WConfig;
			qSPRApp.InitializeComponent();
			qSPRApp.WPFTestTreeWindowCollection.ttdWpfTreeView._scheduler.GlobalStatus.ApplicationLoaded = true;
			qSPRApp.Run();
			Analytics.CloseAnalyticsFile();
			return QSPRMainWindow.ExitCode;
		}
		catch (SecurityException ex)
		{
			TraceMessage.WriteAlways("QC.QTMApplication.QTM", "Main Security Exception" + ex.ToString(), TraceMessageType.Exception);
			AppMessageDialog.Show("This application must be fully trusted to implement plugin functionality. Please run from a local drive.", "Insufficient Permissions", DialogResult.OK, MessageDialogType.CriticalException);
		}
		catch (Exception ex2)
		{
			TraceMessage.WriteAlways("QC.QTMApplication.QTM", "Main " + ex2.ToString(), TraceMessageType.Exception);
			AppMessageDialog.Show("ERROR: " + ex2.ToString(), "QSPR - Message Center", MessageBoxButtons.OK, MessageBoxIcon.Hand, DialogResult.OK, MessageDialogType.CriticalException);
		}
		return -1;
	}

	private static bool LoadWConfig(out WorkspaceConfig WConfig)
	{
		TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp", "LoadWConfig", TraceMessageType.Trace);
		FileStream fileStream = null;
		bool result = true;
		WConfig = null;
		try
		{
			string text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), Path.Combine(QSPRMainWindow.FeatureConfigInfo.ConfigDirectory, "Workspace.config"));
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(WorkspaceConfig));
			if (File.Exists(text))
			{
				fileStream = new FileStream(text, FileMode.Open, FileAccess.Read, FileShare.Read);
				if (fileStream != null)
				{
					TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp", "Loading config from " + text, TraceMessageType.Trace);
					WorkspaceConfig workspaceConfig = (WorkspaceConfig)xmlSerializer.Deserialize(fileStream);
					WConfig = workspaceConfig;
					fileStream.Close();
				}
			}
			else
			{
				TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp", "No config file found reverting to default config ", TraceMessageType.Trace);
				WConfig = new WorkspaceConfig();
			}
		}
		catch (Exception ex)
		{
			WConfig = new WorkspaceConfig();
			result = false;
			TraceMessage.WriteAlways("QC.QTMApplication.QSPRMainWindow.StartApp", "LoadWConfig " + ex.ToString(), TraceMessageType.Exception);
		}
		finally
		{
			fileStream?.Close();
		}
		return result;
	}

	private static void InitPluginDirectories()
	{
		TraceMessage.Write("QC.QTMApplication.QTM", "InitPluginDirectories", TraceMessageType.Trace);
		try
		{
			string text = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), QSPRMainWindow.FeatureConfigInfo.PluginsDirectory);
			Directory.CreateDirectory(text);
			PluginHandler.PluginDirectory = text;
		}
		catch (Exception ex)
		{
			TraceMessage.Write("QC.QTMApplication.QTM", "InitPluginDirectories " + ex.Message, TraceMessageType.Exception);
		}
	}
}
