"""Root URL configuration."""
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import include, path

from documents.views import opening_url, scene_urls


class SceneLoginView(auth_views.LoginView):
    """The stock login view, plus the sign-in scene's photographs."""

    def form_invalid(self, form):
        """Say "wait", not "wrong password", to someone who is locked out.

        The backend refuses either way; this only changes the wording, so an
        owner who mistyped a few times is told what is actually happening
        rather than concluding their password has stopped working. Passed as
        its own context value because the template writes the sign-in error in
        the site's own words instead of rendering Django's."""
        from accounts.throttle import WINDOW_MINUTES, client_ip, locked_out

        identifier = (self.request.POST.get("username") or "").strip()
        if locked_out(identifier, client_ip(self.request)):
            self.lockout_message = (
                "Too many sign-in attempts. Please wait about %d minutes and "
                "try again, or reset your password." % WINDOW_MINUTES)
        return super().form_invalid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["scene_urls"] = scene_urls()
        context["opening_url"] = opening_url()
        context["lockout_message"] = getattr(self, "lockout_message", "")
        return context

# Brand the admin per instance so staff see their own portal's name, not
# "Django administration".
admin.site.site_header = f"{settings.SITE_NAME} — administration"
admin.site.site_title = settings.SITE_NAME
admin.site.index_title = "Manage documents, owners and the board"

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/login/", SceneLoginView.as_view(), name="login"),
    path("accounts/", include("accounts.urls")),
    path("accounts/", include("django.contrib.auth.urls")),
    path("staff/", include("backoffice.urls")),
    path("", include("documents.urls")),
]
