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>
public class RelayHelper
{
    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>
    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>
    public static void PowerOffRelay(Relay relay)
        {
            UriBuilder builder = new()
            {
                Scheme = "https",
                Host = "localhost",
                Port = 7186,
                Path = $"{relay.RelayNumber}/powerOff"
            };
    
            PowerRelay(relay, builder);
        }

    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>
    public static bool GetRelayStatus(Relay relay)
        {
            return false;
        }
}