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

namespace NetworkResurrector.Server.Application.CommandHandlers
{
    public class ShutdownMachineHandler : IRequestHandler<ShutdownMachine, MachineShutdown>
    {
        private readonly ILogger<ShutdownMachineHandler> _logger;
        private readonly IShutdownService _shutdownService;

        public ShutdownMachineHandler(ILogger<ShutdownMachineHandler> logger, IShutdownService shutdownService)
        {
            _logger = logger;
            _shutdownService = shutdownService;
        }

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

        private MachineShutdown Handle(ShutdownMachine command)
        {
            try
            {
                _logger.LogDebug($"Start shutting down '{command.IPAddressOrMachineName}'.");
                var status = _shutdownService.ShutdownMachine(command.IPAddressOrMachineName);
                _logger.LogDebug($"Shutting down machine '{command.IPAddressOrMachineName}' finished. Status: {status}");
                return new MachineShutdown(true, status);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unexpected error has occurred.");
                return new MachineShutdown(false, ex.Message);
            }
        }
    }
}
