using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using QC.QsprShared.Dialogs;

namespace QC.QTMApplication;

internal class CustomExceptionHandler
{
	public void OnUIThreadException(object sender, ThreadExceptionEventArgs t)
	{
		DialogResult dialogResult = DialogResult.Cancel;
		try
		{
			dialogResult = ShowThreadExceptionDialog(t.Exception, "Windows Forms");
		}
		catch
		{
			try
			{
				AppMessageDialog.Show("Fatal Windows Forms Error", "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Hand, DialogResult.Ignore, MessageDialogType.CriticalException);
			}
			finally
			{
				System.Windows.Application.Current.Shutdown();
			}
		}
		if (dialogResult == DialogResult.Abort)
		{
			System.Windows.Application.Current.Shutdown();
		}
	}

	private DialogResult ShowThreadExceptionDialog(Exception e, string generatedFrom)
	{
		string text = "An error occurred from " + generatedFrom + " Source: " + e.Source + "\n Please contact the adminstrator with the following information:\n\n";
		text = string.Concat(text, e.Message, ", InnerException: ", e.InnerException, "\n\nStack Trace:\n", e.StackTrace);
		return AppMessageDialog.Show(text, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Hand, DialogResult.Ignore, MessageDialogType.CriticalException);
	}

	public void OnThreadException(object sender, UnhandledExceptionEventArgs e)
	{
		DialogResult dialogResult = DialogResult.Cancel;
		try
		{
			Exception ex = (Exception)e.ExceptionObject;
			string text = string.Format("An application error occurred from {0}. Please contact the administrator with the following information:\n\n Source:", ex.Source + "\n\nInner Exception:" + ex.InnerException);
			if (!EventLog.SourceExists("ThreadException"))
			{
				EventLog.CreateEventSource("ThreadException", "Application");
			}
			EventLog eventLog = new EventLog();
			eventLog.Source = "QSPR ThreadException";
			eventLog.WriteEntry(text + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace + "\nTargetSite" + ex.TargetSite);
			dialogResult = ShowThreadExceptionDialog(ex, "ThreadException Errors");
		}
		catch (Exception ex2)
		{
			try
			{
				AppMessageDialog.Show("Fatal Non-UI Error", "Fatal Non-UI Error, Could not write the error to the event log. Reason: " + ex2.Message, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Hand, DialogResult.Ignore, MessageDialogType.CriticalException);
			}
			finally
			{
				System.Windows.Application.Current.Shutdown();
			}
		}
		if (dialogResult == DialogResult.Abort)
		{
			System.Windows.Application.Current.Shutdown();
		}
	}
}
