
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django.contrib.auth.decorators import login_required
from django.conf import settings
from modules.system_stats import get_cached_stats, start_background_updater

from . import models

start_background_updater()


@require_GET
def stats_view(request):
    """
    Retourne tout le cache (shm, cpu_info, memory_info, disk_info, updated_at)
    """
    try:
        data = get_cached_stats()
        return JsonResponse(data, safe=False)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=500)


def global_context(request, **ctx):
    return dict(
        app_title=settings.APP_TITLE,
        app_sub_title=settings.APP_SUB_TITLE,
        **ctx
    )

@login_required
def dashboard_view(request):
    ctx = dict(
        devices=models.Device.all_devices(),
        relay=models.Device.all_devices_json(),
        ws_route=settings.RELAY_WEBSOCKET_ROUTE,
        columns=3,

    )
    return render(request, "relay/dashboard.html", context=global_context(request, **ctx))

@login_required
def admin_view(request):
    return render(request, "relay/iframe.html", context=global_context(request, link='/admin/'))

@login_required
def supervisor_view(request):
    return render(request, "relay/iframe.html", context=global_context(request, link='http://relay.local:9001/'))



