from django.contrib.contenttypes.models import ContentType
from rest_framework.reverse import reverse
from rest_framework.routers import APIRootView, DefaultRouter

from apis_core.generic.abc import GenericModel


class CustomAPIRootView(APIRootView):
    """
    The default basic root view for CustomDefaultRouter

    This view lists the output of the default APIRootView of the Django Rest Framework.
    In addition, it injects the routes of the genericmodelapi (those are not hardcoded
    registered but autogenerated based on the models that inherit from GenericModel).
    """

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        for content_type in ContentType.objects.all():
            if content_type.model_class() is not None and issubclass(
                content_type.model_class(), GenericModel
            ):
                route = "apis_core:generic:genericmodelapi-list"
                response.data[reverse(route, args=[content_type]).strip("/")] = reverse(
                    route,
                    args=[content_type],
                    kwargs=kwargs,
                    request=request,
                    format=kwargs.get("format"),
                )
        return response


class CustomDefaultRouter(DefaultRouter):
    """
    The CustomDefaultRouter only diverts from the Django Rest Framework DefaultRouter
    by setting the APIRootView to our CustomAPIRootView.
    """

    APIRootView = CustomAPIRootView
