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

namespace 自救器呼吸器综合检验仪
{
    internal static class AppShutdownCoordinator
    {
        private static int _shutdownRequested;

        public static bool IsShutdownInProgress
        {
            get
            {
                Application application = Application.Current;
                if (application == null)
                {
                    return Interlocked.CompareExchange(ref _shutdownRequested, 0, 0) == 1;
                }

                return Interlocked.CompareExchange(ref _shutdownRequested, 0, 0) == 1
                    || application.Dispatcher.HasShutdownStarted
                    || application.Dispatcher.HasShutdownFinished;
            }
        }

        public static void RequestShutdown()
        {
            Application application = Application.Current;
            if (application == null)
            {
                return;
            }

            if (Interlocked.Exchange(ref _shutdownRequested, 1) == 1)
            {
                return;
            }

            application.Dispatcher.BeginInvoke(
                DispatcherPriority.ApplicationIdle,
                new Action(() =>
                {
                    if (application.Dispatcher.HasShutdownStarted || application.Dispatcher.HasShutdownFinished)
                    {
                        return;
                    }

                    application.Shutdown();
                }));
        }

        public static bool ShouldSuppressDuringShutdown(Exception exception)
        {
            if (!IsShutdownInProgress || exception == null)
            {
                return false;
            }

            return exception is InvalidOperationException || exception is Win32Exception;
        }
    }
}
