"""This module contains the middlewares for the ``licences`` app"""

from django.conf import settings
from django.template.response import SimpleTemplateResponse
from django.utils.deprecation import MiddlewareMixin

from .exceptions import LicenceException


class LicenceMiddleware(MiddlewareMixin):
    """Middleware to intercept the ``LicenceException`` and to return a response to the user"""

    def process_exception(self, request, exception):  # pylint: disable=unused-argument
        """If the exception is a ``LicenceException`` redirect the user to the appropriate url

        Parameters
        ----------
        For the parameters, see:
        - https://docs.djangoproject.com/fr/2.0/topics/http/middleware/#process-exception

        """

        if isinstance(exception, LicenceException):
            return SimpleTemplateResponse(
                template='cms/licences/upgrade.html',
                context={
                    'message': exception.message,
                    'instance_name': settings.INSTANCE_NAME
                }
            )

        return None

