using System.Windows.Threading;
using Valg.EVA.Skanning.ContainerExtensions;
using Prism.Events;

namespace Valg.EVA.Skanning.UserInterfaceElements.ApplicationTermination
{
    public class ApplicationTerminationHandler : IStartableComponent
    {
        private readonly IEventAggregator eventAggregator;

        public ApplicationTerminationHandler(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
        }

        public void Start()
        {
            Dispatcher.CurrentDispatcher.ShutdownStarted += delegate
               {
                   var ev = eventAggregator.GetEvent<ApplicationTerminatingEvent>();
                   ev.Publish(new ApplicationTerminatingEventArgs());
               };

            var terminateRequestedEvent = eventAggregator.GetEvent<ApplicationTerminateRequestedEvent>();
            terminateRequestedEvent.Subscribe(TerminateRequested);
        }

        private void TerminateRequested(System.EventArgs e)
        {
            if (!Dispatcher.CurrentDispatcher.HasShutdownStarted)
            {
                Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
            }
        }
    }
}
