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

namespace NetworkResurrector.Api.Application.CommandHandlers
{
    public class SleepMachineHandler : IRequestHandler<SleepMachine, MachineSlept>
    {
        private readonly ILogger<SleepMachineHandler> _logger;
        private readonly INetworkRepository _repository;
        private readonly IResurrectorAgentService _resurrectorAgentService;
        private readonly IConfiguration _configuration;

        public SleepMachineHandler(ILogger<SleepMachineHandler> logger, INetworkRepository repository, IResurrectorAgentService resurrectorAgentService, IConfiguration configuration)
        {
            _logger=logger;
            _repository=repository;
            _resurrectorAgentService=resurrectorAgentService;
            _configuration=configuration;
        }

        public async Task<MachineSlept> Handle(SleepMachine command, CancellationToken cancellationToken)
        {
            _logger.LogDebug($"Start sleeping machine {command.MachineId}");
            var machine = await _repository.GetMachine(command.MachineId);
            var powerConfiguration = await _repository.GetPowerActionConfiguration(command.MachineId, PowerActions.SLEEP);

            //log activity

            var ipAddressOrMachineName = machine.IPv4Address ?? machine.MachineName;
            MachineSlept result;

            switch (powerConfiguration.Performer.PerformerCode)
            {
                case PowerActionPerformers.NETWORK_RESURRECTOR_AGENT:
                    if (machine.Agent == null)
                        throw new Exception($"Cannot use network resurrector agent as sleep performer for machine '{ipAddressOrMachineName}' because it is not configured.");

                    var owner = new ActionOwner(_configuration.GetValue<string>("Service:Code"));
                    var options = new ActionOptions(command.Delay ?? 0, command.Force);
                    var sleepResultByAgent = await _resurrectorAgentService.Sleep(ipAddressOrMachineName, machine.Agent.AgentPort, owner, options);
                    var status = sleepResultByAgent.Success ? $"Machine '{ipAddressOrMachineName}' successfully slept." : $"Machine '{ipAddressOrMachineName}' could not be slept.";
                    result = new MachineSlept(sleepResultByAgent.Success, status);
                    break;

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

            _logger.LogDebug($"Machine {command.MachineId} sleeping finished. Success: {result.Success}; Status: {result.Status}");

            return result;
        }
    }
}
