using MediatR;
using Microsoft.Extensions.Logging;
using NetworkResurrector.Server.Abstractions;
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 WakeMachineHandler : IRequestHandler<WakeMachine, MachineWaked>
    {
        private readonly ILogger<WakeMachineHandler> _logger;
        private readonly IWakeOnLanService _wakeOnLanService;

        public WakeMachineHandler(ILogger<WakeMachineHandler> logger, IWakeOnLanService wakeOnLanService)
        {
            _logger = logger;
            _wakeOnLanService = wakeOnLanService;
        }

        public async Task<MachineWaked> Handle(WakeMachine command, CancellationToken cancellationToken)
        {
            try
            {
                var (success, status) = await _wakeOnLanService.Wake(command.MacAddress);
                return new MachineWaked(success, status);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unexpected error has occurred.");
                return new MachineWaked(false, ex.Message);
            }
        }
    }
}