using MediatR;
using Microsoft.Extensions.Logging;
using NetworkResurrector.Api.Application.Extensions;
using NetworkResurrector.Api.Application.Services.Abstractions;
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 WakeMachineHandler : IRequestHandler<WakeMachine, MachineWaked>
    {
        private readonly ILogger<WakeMachineHandler> _logger;
        private readonly IResurrectorService _resurrectorService;
        private readonly INetworkRepository _repository;
        private readonly INotificationService _notificationService;

        public WakeMachineHandler(ILogger<WakeMachineHandler> logger, IResurrectorService resurrectorService, INetworkRepository repository, INotificationService notificationService)
        {
            _logger=logger;
            _resurrectorService=resurrectorService;
            _repository=repository;
            _notificationService=notificationService;
        }

        public async Task<MachineWaked> Handle(WakeMachine command, CancellationToken cancellationToken)
        {
            _logger.LogDebug($"Start waking up machine {command.MachineId}");
            var machine = await _repository.GetMachine(command.MachineId);
            var powerConfiguration = await _repository.GetPowerActionConfiguration(command.MachineId, PowerActions.WAKE);

            //log activity

            MachineWaked result;
            var performer = powerConfiguration.Performer.PerformerCode;
            switch (performer)
            {
                case PowerActionPerformers.NETWORK_RESURRECTOR_SERVER:
                    var wakeResult = await _resurrectorService.Wake(machine.MACAddress);
                    result = new MachineWaked(wakeResult.Success, wakeResult.Status);
                    _logger.LogDebug($"Machine {command.MachineId} wake up finished. Success: {result.Success}; Status: {result.Status}");
                    break;

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

            var notificationContext = machine.ToNotificationContext(result.Status, performer);
            await _notificationService.Notify(NotificationType.Wake, notificationContext, cancellationToken);
            return result;
        }
    }
}
