using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

namespace SurfacePlot3D.Statics
{
    public static class UIServices
    {
        public static void DoEvents()
        {
            if (Application.Current == null) return;
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
        }

        public static void DoEventsRender()
        {
            if (Application.Current == null) return;
            Application.Current.Dispatcher.Invoke(delegate () { }, DispatcherPriority.Render);
        }

        private static bool IsBusy;

        public static void Busy()
        {
            SetBusyState(true);
        }
        public static void SetBusyState()
        {
            SetBusyState(true);
        }

        private static void SetBusyState(bool busy)
        {
            if (busy != IsBusy)
            {
                IsBusy = busy;
                Application.Current.Dispatcher.Invoke(() => { Mouse.OverrideCursor = busy ? Cursors.Wait : null; });
                if (IsBusy) new DispatcherTimer(TimeSpan.FromSeconds(0), DispatcherPriority.ApplicationIdle, dispatcherTimer_Tick, System.Windows.Application.Current.Dispatcher);
            }
        }

        private static void dispatcherTimer_Tick(Object sender, System.EventArgs e)
        {
            var dispatcherTimer = sender as DispatcherTimer;
            if (dispatcherTimer != null)
            {
                SetBusyState(false);
                dispatcherTimer.Stop();
            }
        }
    }
}