//  Copyright (c) Microsoft Corporation.  All rights reserved.

namespace Microsoft.VisualStudio.TestTools.TestCaseMigrator
{
    using System;
    using System.Windows.Input;

    /// <summary>
    /// This is a class to help display a busy cursor during long operations
    /// that will automatically revert to a "normal" cursor when it's through.
    internal class AutoWaitCursor : IDisposable
    {
        #region Constructor

        public AutoWaitCursor()
        {
            App.CallMethodInUISynchronizationContext(ShowWaitCursor, null);
        }

        #endregion

        #region Public Methods

        // Flag used to don't show waiting cursor during console mode
        public static bool IsConsoleMode = false;

        void IDisposable.Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        #endregion

        #region Private methods

        private static void ShowWaitCursor(object value)
        {
            try
            {
                if (!IsConsoleMode)
                {
                    Mouse.OverrideCursor = Cursors.Wait;
                }
            }
            catch (InvalidOperationException)
            { }
        }

        void Dispose(bool disposing)
        {
            App.CallMethodInUISynchronizationContext(RestoreNormalCursor, disposing);
        }

        private static void RestoreNormalCursor(object disposing)
        {
            try
            {
                if ((bool)disposing && !IsConsoleMode)
                {
                    Mouse.OverrideCursor = null;
                }
            }
            catch (InvalidOperationException)
            { }
        }

        #endregion
    }
}
