using Microsoft.Win32;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusBluetoothInfoService
{
    public NexusBluetoothSnapshot Capture()
    {
        var enabled = IsBluetoothEnabled();
        var devices = enabled ? ReadPairedDevices() : [];
        return new NexusBluetoothSnapshot
        {
            Status = enabled ? "Bluetooth er aktiv" : "Bluetooth er slået fra eller utilgængelig",
            PairedDevices = devices,
        };
    }

    private static bool IsBluetoothEnabled()
    {
        try
        {
            using var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters");
            if (key is null)
            {
                return false;
            }

            var radios = key.GetValue("RadioEnable");
            if (radios is int radio && radio == 0)
            {
                return false;
            }

            return true;
        }
        catch
        {
            return false;
        }
    }

    private static List<string> ReadPairedDevices()
    {
        var devices = new List<string>();
        try
        {
            using var root = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices");
            if (root is null)
            {
                return devices;
            }

            foreach (var subKeyName in root.GetSubKeyNames())
            {
                using var sub = root.OpenSubKey(subKeyName);
                var name = sub?.GetValue("Name") as string;
                if (!string.IsNullOrWhiteSpace(name))
                {
                    devices.Add(name.Trim());
                }
            }
        }
        catch
        {
            // POC: ignore
        }

        return devices
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .OrderBy(static n => n, StringComparer.OrdinalIgnoreCase)
            .ToList();
    }
}
