import logging

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

from mini_buildd.config import URIS, Uri
import mini_buildd.admin
from mini_buildd.views import DefaultView, DirView, EventsView, BuildsView, RepositoriesView, BuildersView, APIView, SetupView, LogView, AccountRegisterView, AccountActivateView, AccountProfileView, ExceptionMiddleware

LOG = logging.getLogger(__name__)


def mbd_path(route, uri="view", view_cls=DefaultView):
    uri_obj = 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.info(f"Adding url: {name} -> {uri_obj}")
    return path_func(uri_obj.django(), view_cls.as_view(), kwargs={"route": route, "name": name}, name=name)


# pylint: disable=invalid-name
urlpatterns = [
    # Redirect
    path("", django.views.generic.base.RedirectView.as_view(url=URIS["home"]["view"].django())),

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

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

    # /mini_buildd/
    mbd_path("home"),
    mbd_path("events", view_cls=EventsView),
    mbd_path("events", uri="dir", view_cls=DirView),
    mbd_path("builds", view_cls=BuildsView),
    mbd_path("builds", uri="dir", view_cls=DirView),
    mbd_path("repositories", view_cls=RepositoriesView),
    mbd_path("repositories", uri="dir", view_cls=DirView),
    mbd_path("builders", view_cls=BuildersView),
    mbd_path("crontab"),
    mbd_path("api"),
    mbd_path("sitemap"),
    mbd_path("manual"),
    mbd_path("setup", view_cls=SetupView),
    mbd_path("log", view_cls=LogView),
]

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

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