using System.Net;
using System.Web;
using adas_core.Domain.Models.MongoModels;
using Serilog;

namespace adas_core.Domain.Utils;

/// <summary>
/// Provides helper methods for relaying operations, data, or commands between components.
/// </summary>
/// <!-- aidoc:v1 sig=00f0997 -->
public class RelayHelper
{
    /// <summary>
    /// Retrieves the current status of a <see cref="Relay"/> by calling a local REST API endpoint built from its connection parameters, returning <see langword="true"/> when the relay is reported as active and <see langword="false"/> when the response is not <see cref="HttpStatusCode.OK"/>, the payload cannot be converted to a boolean, or any exception is raised during the request.
    /// </summary>
    /// <param name="relay">The <see cref="Relay"/> whose status is queried; its <see cref="Relay.RelayNumber"/> is used in the URL path while <see cref="Relay.Driver"/>, <see cref="Relay.Ip"/>, and <see cref="Relay.Port"/> are passed as query parameters.</param>
    /// <returns><see langword="true"/> if the API responds with <see cref="HttpStatusCode.OK"/> and the response body converts to a boolean value of <see langword="true"/>; otherwise, <see langword="false"/>.</returns>
    /// <!-- aidoc:v1 sig=0240829 body=a1db00d -->
    public static bool GetRelayStatusFromApiRest(Relay relay)
    {
        UriBuilder builder = new()
        {
            Scheme = "https",
            Host = "localhost",
            Port = 7186,
            Path = $"{relay.RelayNumber}/status"
        };

        var query = HttpUtility.ParseQueryString(builder.Query);
        query["driver"] = relay.Driver;
        query["host"] = relay.Ip;
        query["port"] = relay.Port.ToString();
        query["relays"] = "8"; //todo:tendría que recoger el total

        builder.Query = query.ToString();
        HttpRequestMessage request = new()
        {
            RequestUri = builder.Uri,
            Method = HttpMethod.Get
        };


        try
        {
            using var client = new HttpClient();
            var httpResponse = client.SendAsync(request).Result;

            if (httpResponse.StatusCode.Equals(HttpStatusCode.OK))
            {
                var responseContent = httpResponse.Content;
                var response = responseContent.ReadAsStringAsync().Result;


                return Convert.ToBoolean(response);
            }

            return false;
        }
        catch (Exception e)
        {
            Log.Debug("Exception Getting Relay Status From Api Rest: {relay}", e);
            return false;
        }
    }


    //TODO son provisionales mientras se añade como nuget Smacs.Divers
    /// <summary>
    /// Powers on the specified relay by constructing a request to the local relay control endpoint at https://localhost:7186, where the relay is identified by its <see cref="Relay.RelayNumber"/> in the path.
    /// </summary>
    /// <param name="relay">The relay to power on.</param>
    /// <!-- aidoc:v1 sig=61b2177 body=b5539f2 -->
    public static void PowerOnRelay(Relay relay)
        {
            UriBuilder builder = new()
            {
                Scheme = "https",
                Host = "localhost",
                Port = 7186,
                Path = $"{relay.RelayNumber}/powerOn"
            };
    
            PowerRelay(relay, builder);
        }

    /// <summary>
    /// Sends a power off command to the specified relay by building a request to the local relay control endpoint
    /// using the relay's number as the path identifier, then forwarding the call to the underlying relay handler.
    /// </summary>
    /// <param name="relay">The relay to power off, identified by its <see cref="Relay.RelayNumber"/> which is used to construct the request path.</param>
    /// <!-- aidoc:v1 sig=3bafafd body=1a09ab5 -->
    public static void PowerOffRelay(Relay relay)
        {
            UriBuilder builder = new()
            {
                Scheme = "https",
                Host = "localhost",
                Port = 7186,
                Path = $"{relay.RelayNumber}/powerOff"
            };
    
            PowerRelay(relay, builder);
        }

    /// <summary>
    /// Sends an HTTP POST request to power a <see cref="Relay"/> through the endpoint described by <paramref name="builder"/>, enriching the query string with the relay's driver, IP address, port, and a fixed channel count of 8. Logs an information message when the response status is not <see cref="HttpStatusCode.OK"/> and logs any exception raised during the call at debug level instead of propagating it.
    /// </summary>
    /// <param name="relay">The relay to power, whose <see cref="Relay.Driver"/>, <see cref="Relay.Ip"/> and <see cref="Relay.Port"/> values are written into the request query string.</param>
    /// <param name="builder">The <see cref="UriBuilder"/> whose query string is populated and whose <see cref="UriBuilder.Uri"/> identifies the target endpoint of the POST request.</param>
    /// <!-- aidoc:v1 sig=01d6944 body=089ce17 -->
    private static void PowerRelay(Relay relay, UriBuilder builder)
    {
        var query = HttpUtility.ParseQueryString(builder.Query);
        query["driver"] = relay.Driver;
        query["host"] = relay.Ip;
        query["port"] = relay.Port.ToString();
        query["relays"] = "8"; //todo:tendría que recoger el total

        builder.Query = query.ToString();
        HttpRequestMessage request = new()
        {
            RequestUri = builder.Uri,
            Method = HttpMethod.Post
        };

        try
        {
            using var client = new HttpClient();
            var httpResponse = client.SendAsync(request).Result;

            if (!httpResponse.StatusCode.Equals(HttpStatusCode.OK)) Log.Information("relay: {relay} powered", relay);
        }
        catch (Exception e)
        {
            Log.Debug("Exception {e} powering Relay: {relay}", e.Message, relay);
        }
    }


    /// <summary>
    /// Retrieves the current status of the specified relay. Currently always returns <c>false</c>, indicating the relay status is not available or is treated as inactive.
    /// </summary>
    /// <param name="relay">The relay whose status is being queried.</param>
    /// <returns><c>true</c> if the relay is active; otherwise, <c>false</c>.</returns>
    /// <!-- aidoc:v1 sig=d491189 body=90f8ab6 -->
    public static bool GetRelayStatus(Relay relay)
        {
            return false;
        }
}