using MediatR;
using Microsoft.Extensions.Logging;
using NetworkResurrector.Agent.Application.Services.Abstractions;
using NetworkResurrector.Agent.PublishedLanguage.Commands;
using NetworkResurrector.Agent.PublishedLanguage.Events;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace NetworkResurrector.Agent.Application.CommandHandlers
{
    public class CancelHandler : IRequestHandler<Cancel, CancelResult>
    {
        private readonly ILogger<CancelHandler> _logger;
        private readonly IPowerService _powerService;
        private readonly IValidationService _validationService;

        public CancelHandler(ILogger<CancelHandler> logger, IPowerService powerService, IValidationService validationService)
        {
            _logger=logger;
            _powerService=powerService;
            _validationService=validationService;
        }

        public async Task<CancelResult> Handle(Cancel command, CancellationToken cancellationToken)
        {
            return await Task.Run(() => Handle(command));
        }

        private CancelResult Handle(Cancel command)
        {
            _validationService.ValidateRestrictions(command.Owner);

            _logger.LogDebug($"Start canceling the previous action.");

            var stopWatch = new Stopwatch();
            stopWatch.Start();

            _powerService.Cancel();

            stopWatch.Stop();
            _logger.LogDebug($"Action cancellation finished - {stopWatch.ElapsedMilliseconds:N0} ms");

            return new CancelResult() { Success = true };
        }
    }
}
