using MediatR;
using Microsoft.Extensions.Logging;
using NetworkResurrector.Api.Domain.Constants;
using NetworkResurrector.Api.Domain.Repositories;
using NetworkResurrector.Api.PublishedLanguage.Commands;
using NetworkResurrector.Api.PublishedLanguage.Events;
using NetworkResurrector.Server.Wrapper.Services;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace NetworkResurrector.Api.Application.CommandHandlers
{
    public class PingMachineHandler : IRequestHandler<PingMachine, MachinePinged>
    {
        private readonly ILogger<PingMachineHandler> _logger;
        private readonly IResurrectorService _resurrectorService;
        private readonly INetworkRepository _repository;

        public PingMachineHandler(ILogger<PingMachineHandler> logger, IResurrectorService resurrectorService, INetworkRepository repository)
        {
            _logger=logger;
            _resurrectorService=resurrectorService;
            _repository=repository;
        }

        public async Task<MachinePinged> Handle(PingMachine command, CancellationToken cancellationToken)
        {
            _logger.LogDebug($"Start pinging machine {command.MachineId}");
            var machine = await _repository.GetMachine(command.MachineId);
            var powerConfiguration = await _repository.GetPowerActionConfiguration(command.MachineId, PowerActions.PING);

            //log activity

            MachinePinged result;
            switch (powerConfiguration.Performer.PerformerCode)
            {
                case PowerActionPerformers.NETWORK_RESURRECTOR_SERVER:
                    var pingResult = await _resurrectorService.Ping(machine.IPv4Address ?? machine.MachineName);
                    result = new MachinePinged(pingResult.Success, pingResult.Status);
                    _logger.LogDebug($"Machine {command.MachineId} pinging finished. Success: {result.Success}; Status: {result.Status}");
                    break;

                default:
                    throw new Exception($"Power action performer {powerConfiguration.Performer.PerformerCode} is not implemented.");
            }

            return result;
        }
    }
}
