using System.Net;
using System.Net.Sockets;
using InnovEnergy.Lib.Protocols.DBus.Transport;

namespace InnovEnergy.Lib.Protocols.DBus;

public readonly record struct Bus(EndPoint EndPoint, AuthenticationMethod Auth)
{
    public static Bus System  => new Bus(new UnixDomainSocketEndPoint(SystemBusAddress)  , AuthenticationMethod.External());
    public static Bus Session => new Bus(new UnixDomainSocketEndPoint(SessionBusAddress!), AuthenticationMethod.External()); // TODO

    private const String DefaultSystemBusSocket = "/var/run/dbus/system_bus_socket";

    // TODO: properly parse address
    private static String? SessionBusAddress => GetEnvironmentVariable("DBUS_SESSION_BUS_ADDRESS")?.Replace("unix:path=","");
    private static String  SystemBusAddress  => GetEnvironmentVariable("DBUS_SYSTEM_BUS_ADDRESS") ?? DefaultSystemBusSocket;

    private static String? GetEnvironmentVariable(String name)
    {
        var v = Environment.GetEnvironmentVariable(name);
        return String.IsNullOrWhiteSpace(v) ? null : v;
    }

    public override String? ToString() => EndPoint.ToString();
}