"""Tests for the dashboard-widgets hook consumer (/api/dashboard/widgets).

Pins the wiring added for the BasePlugin.get_dashboard_widgets hook: the
endpoint aggregates enabled plugins' widgets and skips disabled ones.

Plugin enabled-state is monkeypatched (not persisted) so these tests do not
mutate the shared instance/plugins.json registry file.
"""


def _widget_plugins(client, headers):
    response = client.get('/api/dashboard/widgets', headers=headers)
    assert response.status_code == 200, response.get_json()
    widgets = response.get_json()['data']
    assert isinstance(widgets, list)
    return widgets, {w.get('plugin') for w in widgets}


def test_widgets_endpoint_aggregates_enabled_plugins(app, client, auth_headers,
                                                     monkeypatch):
    """An enabled plugin that implements the hook contributes a widget."""
    pm = app.extensions['plugin_manager']
    monkeypatch.setattr(pm.registry, 'is_enabled', lambda name: True)

    widgets, plugins = _widget_plugins(client, auth_headers)
    assert 'computers' in plugins  # computers implements get_dashboard_widgets
    positions = [w.get('position', 99) for w in widgets]
    assert positions == sorted(positions)


def test_widgets_endpoint_skips_disabled_plugin(app, client, auth_headers,
                                                monkeypatch):
    """A disabled plugin's widgets drop out of the aggregate."""
    pm = app.extensions['plugin_manager']
    monkeypatch.setattr(pm.registry, 'is_enabled', lambda name: name != 'computers')

    _, plugins = _widget_plugins(client, auth_headers)
    assert 'computers' not in plugins
