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 PingMachineHandler : IRequestHandler<PingMachine, MachinePinged>
    {
        private readonly ILogger<PingMachineHandler> _logger;
        private readonly IPingService _pingService;

        public PingMachineHandler(ILogger<PingMachineHandler> logger, IPingService pingService)
        {
            _logger = logger;
            _pingService = pingService;
        }

        public async Task<MachinePinged> Handle(PingMachine command, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug($"Start pinging '{command.IpAddressOrMachineName}'.");
                var (success, status) = await _pingService.PingMachine(command.IpAddressOrMachineName);
                _logger.LogDebug($"Pinging on '{command.IpAddressOrMachineName}' finished. Status: {status}");
                return new MachinePinged(success, status);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unexpected error has occurred.");
                return new MachinePinged(false, ex.Message);
            }
        }
    }
}
