using System;
using System.Threading;

namespace QC.QSPR.Threading;

public class Shutdown
{
	private static Shutdown singleton = new Shutdown();

	private static EventWaitHandle waitHandle = new ManualResetEvent(initialState: false);

	public static EventWaitHandle WaitHandle => waitHandle;

	public static bool IsSignaled => waitHandle.WaitOne(0, exitContext: false);

	private Shutdown()
	{
		AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
		if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
		{
			AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
		}
	}

	private void CurrentDomain_DomainUnload(object sender, EventArgs e)
	{
		SignalShutdown();
	}

	private void CurrentDomain_ProcessExit(object sender, EventArgs e)
	{
		SignalShutdown();
	}

	public static void SignalShutdown()
	{
		WaitHandle.Set();
	}
}
