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 LogoutHandler : IRequestHandler<Logout, LogoutResult>
    {
        private readonly ILogger<LogoutHandler> _logger;
        private readonly IPowerService _powerService;
        private readonly IValidationService _validationService;

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

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

        private LogoutResult Handle(Logout command)
        {
            _validationService.ValidateRestrictions(command.Owner);

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

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

            _powerService.Logout();

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

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