from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from wagtail.models import Site

from .services import get_settings_for_site, get_status_summary


@staff_member_required
def dashboard(request):
    selected_site_id = request.GET.get("site_id")
    if selected_site_id:
        site = get_object_or_404(Site, pk=selected_site_id)
    else:
        site = Site.objects.get(is_default_site=True)
    mobile_app = get_settings_for_site(site)
    context = {
        "sites": Site.objects.order_by("hostname"),
        "selected_site": site,
        **get_status_summary(site, mobile_app),
    }
    return TemplateResponse(
        request,
        "wagtailadmin/mobileapp/dashboard.html",
        context,
    )
