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 LockHandler : IRequestHandler<Lock, LockResult>
    {
        private readonly ILogger<LockHandler> _logger;
        private readonly IPowerService _powerService;
        private readonly IValidationService _validationService;

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

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

        private LockResult Handle(Lock command)
        {
            _validationService.ValidateRestrictions(command.Owner);

            _logger.LogDebug($"Start locking the user.");

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

            _powerService.Lock();

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

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