using System;
using System.Threading;

namespace QC.QSPR.Threading;

public class EventOnSignal<TEventArgs> : AbortableObject where TEventArgs : EventArgs
{
	private TEventArgs args;

	private EventWaitHandle waitHandle;

	private bool waiting;

	public event EventHandler<TEventArgs> EventSignaled;

	public EventOnSignal(EventWaitHandle signalWaitHandle, TEventArgs argsToPass)
	{
		args = argsToPass;
		waitHandle = signalWaitHandle;
		Reset();
	}

	public void Reset()
	{
		Reset(args);
	}

	public void Reset(TEventArgs newArgs)
	{
		args = newArgs;
		if (!waiting)
		{
			ResetAbort();
			Thread thread = new Thread(WaitForSignal);
			thread.Start();
		}
	}

	protected void WaitForSignal()
	{
		waiting = true;
		int num = WaitHandle.WaitAny(new WaitHandle[2] { waitHandle, base.AbortEvent });
		waiting = false;
		switch (num)
		{
		case 0:
			this.EventSignaled?.Invoke(this, args);
			break;
		case 1:
			base.AbortCompleteEvent.Set();
			break;
		}
	}
}
