using System.Diagnostics;
using Microsoft.Win32;

namespace Dada.Supervisor;

internal static class SupportedBrowserLauncher
{
    internal static bool OpenDefaultSupported(Uri uri) => Open("chrome.exe", uri) || Open("msedge.exe", uri);
    internal static bool OpenChrome(Uri uri) => Open("chrome.exe", uri);
    internal static bool OpenEdge(Uri uri) => Open("msedge.exe", uri);

    private static bool Open(string executableName, Uri uri)
    {
        var executable = FindExecutable(executableName);
        if (executable is null) return false;
        var startInfo = new ProcessStartInfo(executable) { UseShellExecute = false };
        startInfo.ArgumentList.Add(uri.AbsoluteUri);
        Process.Start(startInfo);
        return true;
    }

    private static string? FindExecutable(string executableName)
    {
        foreach (var hive in new[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine })
        foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 })
        {
            using var baseKey = RegistryKey.OpenBaseKey(hive, view);
            using var key = baseKey.OpenSubKey($"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\{executableName}");
            if (key?.GetValue(null) is string path && File.Exists(path)) return path;
        }
        return null;
    }
}
