using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusDisplayService
{
    private readonly DisplaySettingsService _displaySettings;

    public NexusDisplayService(DisplaySettingsService displaySettings)
    {
        _displaySettings = displaySettings;
    }

    public IReadOnlyList<NexusDisplaySnapshot> GetDisplays()
    {
        var monitors = _displaySettings.GetMonitors();
        if (monitors.Count == 0)
        {
            return [];
        }

        var maxWidth = monitors.Max(static m => m.CurrentWidth);
        var maxHeight = monitors.Max(static m => m.CurrentHeight);
        var scale = Math.Min(280d / Math.Max(maxWidth, 1), 160d / Math.Max(maxHeight, 1));

        var result = new List<NexusDisplaySnapshot>();
        var offsetX = 0d;

        foreach (var monitor in monitors.OrderByDescending(static m => m.IsPrimary))
        {
            result.Add(new NexusDisplaySnapshot
            {
                Name = monitor.FriendlyName,
                Resolution = $"{monitor.CurrentWidth} × {monitor.CurrentHeight}",
                RefreshRate = monitor.RefreshRate,
                IsPrimary = monitor.IsPrimary,
                LayoutLeft = offsetX,
                LayoutTop = monitor.IsPrimary ? 0 : 20,
                LayoutWidth = monitor.CurrentWidth * scale,
                LayoutHeight = monitor.CurrentHeight * scale,
            });

            offsetX += monitor.CurrentWidth * scale + 24;
        }

        return result;
    }
}
