using System;
using System.ComponentModel;
using System.Threading;

namespace System.Reactive.PlatformServices
{
	[EditorBrowsable(EditorBrowsableState.Never)]
	public static class HostLifecycleService
	{
		public static event EventHandler<HostSuspendingEventArgs> Suspending;

		public static event EventHandler<HostResumingEventArgs> Resuming;

		public static void AddRef()
		{
			if (Interlocked.Increment(ref HostLifecycleService._refCount) == 1)
			{
				IHostLifecycleNotifications value = HostLifecycleService.Notifications.Value;
				if (value != null)
				{
					value.Suspending += new EventHandler<HostSuspendingEventArgs>(HostLifecycleService.OnSuspending);
					value.Resuming += new EventHandler<HostResumingEventArgs>(HostLifecycleService.OnResuming);
				}
			}
		}

		public static void Release()
		{
			if (Interlocked.Decrement(ref HostLifecycleService._refCount) == 0)
			{
				IHostLifecycleNotifications value = HostLifecycleService.Notifications.Value;
				if (value != null)
				{
					value.Suspending -= new EventHandler<HostSuspendingEventArgs>(HostLifecycleService.OnSuspending);
					value.Resuming -= new EventHandler<HostResumingEventArgs>(HostLifecycleService.OnResuming);
				}
			}
		}

		private static void OnSuspending(object sender, object e)
		{
			EventHandler<HostSuspendingEventArgs> suspending = HostLifecycleService.Suspending;
			if (suspending == null)
			{
				return;
			}
			suspending(sender, e);
		}

		private static void OnResuming(object sender, object e)
		{
			EventHandler<HostResumingEventArgs> resuming = HostLifecycleService.Resuming;
			if (resuming == null)
			{
				return;
			}
			resuming(sender, e);
		}

		private static IHostLifecycleNotifications InitializeNotifications()
		{
			return PlatformEnlightenmentProvider.Current.GetService<IHostLifecycleNotifications>(Array.Empty<object>());
		}

		private static readonly Lazy<IHostLifecycleNotifications> Notifications = new Lazy<IHostLifecycleNotifications>(new Func<IHostLifecycleNotifications>(HostLifecycleService.InitializeNotifications));

		private static int _refCount;
	}
}
