import logging

import django.conf.urls
import django.views.generic.base
from django.urls import include, path, re_path

from mini_buildd import admin, api, config, views

LOG = logging.getLogger(__name__)

HOME_VIEW = django.views.generic.base.RedirectView.as_view(url=config.URIS["events"]["view"].uri)


def mbd_path(route, uri="view", view_cls=views.DefaultView):
    uri_obj = config.URIS[route][uri]
    name = route if uri == "view" else f"{route}-{uri}"
    path_func = re_path if uri_obj.django_with_path else path
    LOG.debug("Adding url: %s -> %s", name, uri_obj)
    return path_func(uri_obj.django(), view_cls.as_view(), kwargs={"route": route, "name": name}, name=name)


urlpatterns = [
    # Redirect
    path("", HOME_VIEW),
    path("mini_buildd/", HOME_VIEW),

    # /admin
    path(config.URIS["admin"]["view"].django(), admin.site.urls),

    # /accounts/
    path(config.URIS["accounts"]["register"].django(), views.AccountRegisterView.as_view(), name="register"),
    path(config.URIS["accounts"]["activate"].django() + "<uidb64>/<token>/", views.AccountActivateView.as_view(), name="activate"),
    path(config.URIS["accounts"]["profile"].django(), views.AccountProfileView.as_view(), name="profile"),
    path(config.URIS["accounts"]["null"].django(), views.AccountNullView.as_view(), name="null"),
    path(config.URIS["accounts"]["base"].django(), include("django.contrib.auth.urls")),

    # /mini_buildd/
    mbd_path("events", view_cls=views.EventsView),
    mbd_path("events", uri="dir", view_cls=views.DirView),
    mbd_path("builds", uri="dir", view_cls=views.DirView),
    mbd_path("repositories", view_cls=views.RepositoriesView),
    mbd_path("repositories", uri="dir", view_cls=views.DirView),
    mbd_path("builders", view_cls=views.BuildersView),
    mbd_path("crontab"),
    mbd_path("api"),
    mbd_path("sitemap"),
    mbd_path("manual", view_cls=views.ManualView),
    mbd_path("manual", uri="static", view_cls=views.ManualView),
    mbd_path("setup", view_cls=views.SetupView),
]

# /mini_buildd/api/<call>/
for _NAME, _CALL in api.CALLS.items():
    _URI = config.Uri(_CALL.uri())
    LOG.debug("Adding API route: %s: %s", _NAME, _URI)
    urlpatterns.append(path(_URI.django(), views.APIView.as_view(), kwargs={"call": _CALL}, name=f"apicall_{_NAME}"))

django.conf.urls.handler400 = views.ExceptionMiddleware.bad_request
django.conf.urls.handler403 = views.ExceptionMiddleware.permission_denied
django.conf.urls.handler404 = views.ExceptionMiddleware.page_not_found
django.conf.urls.handler500 = views.ExceptionMiddleware.server_error
