// PRE-GENERATED (design session). Polls the default output device name; raises DeviceChanged.
// Feeds SwitchRuleEvaluator for per-device auto-switching (M12). NAudio — untested here.
using System;
using System.Windows.Threading;
using NAudio.CoreAudioApi;

namespace DansoriEQ.App.Switching;

public sealed class DefaultDeviceWatcher : IDisposable
{
    private readonly MMDeviceEnumerator _enum = new();
    private readonly DispatcherTimer _timer;
    private string? _last;

    public event Action<string>? DeviceChanged;

    public DefaultDeviceWatcher(double intervalMs = 2000)
    {
        _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(intervalMs) };
        _timer.Tick += (_, __) => Poll();
    }

    public void Start() => _timer.Start();
    public void Stop() => _timer.Stop();

    private void Poll()
    {
        try
        {
            var d = _enum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            var name = d.FriendlyName;
            if (!string.Equals(name, _last, StringComparison.OrdinalIgnoreCase))
            {
                _last = name;
                DeviceChanged?.Invoke(name);
            }
        }
        catch { /* no default device / transient */ }
    }

    public void Dispose()
    {
        _timer.Stop();
        _enum.Dispose();
    }
}
