using System.Runtime.Versioning;
using Microsoft.Win32;

namespace RioJoy.Tray.Os;

/// <summary>
/// Manages the Windows "run at login" registration via the per-user
/// <c>Run</c> registry key. Per-user (HKCU) needs no elevation and matches the
/// tray app running in the interactive session.
/// </summary>
[SupportedOSPlatform("windows")]
public static class AutoStartManager
{
    private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
    private const string ValueName = "RIOJoy";

    public static bool IsEnabled()
    {
        using RegistryKey? key = Registry.CurrentUser.OpenSubKey(RunKey);
        return key?.GetValue(ValueName) is not null;
    }

    public static void SetEnabled(bool enabled)
    {
        using RegistryKey key = Registry.CurrentUser.CreateSubKey(RunKey);
        if (enabled)
            key.SetValue(ValueName, $"\"{Environment.ProcessPath}\"");
        else
            key.DeleteValue(ValueName, throwOnMissingValue: false);
    }
}
