using System;
using System.Threading.Tasks;

namespace Valg.EVA.Skanning.UserInterfaceElements.Spinner
{
    public class ProcessRunner<T> : ViewModelBase
    {
        public async Task<T> Run(Func<T> func, string spinnerToolTip, string spinnerText, bool isSpinnerBlocking = true)
        {
            try
            {
                StartSpinner(spinnerToolTip, spinnerText, isSpinnerBlocking);
                var result = await Task.Factory.StartNew(func);
                return result;
            }
            finally
            {
                StopSpinner();
            }
        }

        private void StopSpinner()
        {
            PublishEvent<SpinnerEvent, SpinnerEventArgs>(new SpinnerEventArgs(false));
        }

        private void StartSpinner(string spinnerToolTip, string spinnerText, bool isSpinnerBlocking)
        {
            PublishEvent<SpinnerEvent, SpinnerEventArgs>(new SpinnerEventArgs(true, spinnerToolTip, spinnerText, isSpinnerBlocking));
        }                        
    } 
    public class ProcessRunner : ViewModelBase
    {
        public async void Run(Action action, string spinnerToolTip, string spinnerText, bool isSpinnerBlocking = true)
        {
            try
            {
                StartSpinner(spinnerToolTip, spinnerText, isSpinnerBlocking);
                await Task.Factory.StartNew(action);
            }
            finally
            {
                StopSpinner();
            }
        }

        private void StopSpinner()
        {
            PublishEvent<SpinnerEvent, SpinnerEventArgs>(new SpinnerEventArgs(false));
        }

        private void StartSpinner(string spinnerToolTip, string spinnerText, bool isSpinnerBlocking)
        {
            PublishEvent<SpinnerEvent, SpinnerEventArgs>(new SpinnerEventArgs(true, spinnerToolTip, spinnerText, isSpinnerBlocking));
        }                        
    }
}
