using Netmash.Extensions.Http;
using NetworkResurrector.Server.PublishedLanguage.Commands;
using NetworkResurrector.Server.PublishedLanguage.Dto;
using NetworkResurrector.Server.PublishedLanguage.Events;
using NetworkResurrector.Server.Wrapper.Constants;
using NetworkResurrector.Server.Wrapper.Models;
using NetworkResurrector.Server.Wrapper.Services.Internal;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace NetworkResurrector.Server.Wrapper.Services
{
    internal class ResurrectorService : IResurrectorService
    {
        private const string _contentType = "application/json";
        private readonly HttpClient _httpClient;

        public ResurrectorService(HttpClient httpClient, ServiceConfiguration configuration, HttpHeadersService headersService)
        {
            httpClient.BaseAddress = new Uri(configuration.BaseAddress);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType));

            if (configuration.ForwardHeaders)
            {
                headersService.SetHeadersFromContext(httpClient);
            }

            _httpClient = httpClient;
        }

        public async Task<ServiceVersion> GetServiceVersion()
        {
            var result = await _httpClient.ExecuteGetRequest<ServiceVersion>(ApiRoutes.SystemVersion);
            return result;
        }

        public async Task<MachineWaked> Wake(string macAddress)
        {
            var body = new WakeMachine() { MacAddress = macAddress };
            var result = await _httpClient.ExecutePostRequest<MachineWaked, WakeMachine>(ApiRoutes.Wake, body);
            return result;
        }

        public async Task<MachinePinged> Ping(string ipAddressOrMachineName)
        {
            var body = new PingMachine() { IpAddressOrMachineName = ipAddressOrMachineName };
            var result = await _httpClient.ExecutePostRequest<MachinePinged, PingMachine>(ApiRoutes.Ping, body);
            return result;
        }

        public async Task<MachineShutdown> Shutdown(string ipAddressOrMachineName)
        {
            var body = new ShutdownMachine() { IPAddressOrMachineName = ipAddressOrMachineName };
            var result = await _httpClient.ExecutePostRequest<MachineShutdown, ShutdownMachine>(ApiRoutes.Shutdown, body);
            return result;
        }
    }
}
