using System;
using System.Threading.Tasks;
using Prism.Commands;

namespace Valg.EVA.Skanning.UserInterfaceElements.Commands
{
    public static class GuardedCommand
    {
        public static DelegateCommand Create(Action executeMethod)
        {
            var isExecuting = false;
            var guardedExecution = new Action(() =>
            {
                try
                {
                    isExecuting = true;
                    executeMethod();
                }
                finally
                {
                    isExecuting = false;
                }
            });

            return new DelegateCommand(guardedExecution, () => !isExecuting);
        }

        public static DelegateCommand CreateForAsync(Func<Task> executeMethod)
        {
            var isExecuting = false;
            var guardedExecution = new Action(async () =>
            {
                try
                {
                    isExecuting = true;

                    await executeMethod();
                }
                finally
                {
                    isExecuting = false;
                }
            });

            return new DelegateCommand(guardedExecution, () => !isExecuting);
        }
    }
}
