using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using NetworkResurrector.Agent.Application.Services.Abstractions;
using NetworkResurrector.Agent.Domain.Models;
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 SleepHandler : IRequestHandler<Sleep, SleepResult>
    {
        private readonly ILogger<SleepHandler> _logger;
        private readonly IPowerService _powerService;
        private readonly IValidationService _validationService;
        private readonly IMapper _mapper;

        public SleepHandler(ILogger<SleepHandler> logger, IPowerService powerService, IValidationService validationService, IMapper mapper)
        {
            _logger=logger;
            _powerService=powerService;
            _validationService=validationService;
            _mapper=mapper;
        }

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

        private SleepResult Handle(Sleep command)
        {
            _validationService.ValidateRestrictions(command.Owner);

            _logger.LogDebug($"Start sleeping the system.");

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

            var options = _mapper.Map<PowerOptions>(command.Options);
            _powerService.Sleep(options);

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

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