"""This Middleware compresses the HTML Output at the End. It strips the Spaces
between Tags, an at the beginning and the end of the content."""
from django.utils.html import strip_spaces_between_tags


class CompressHtmlMiddleware(object):
    """This Middleware compresses strips the spaces between tags, and at the
    beginning and the end of the content."""
    # TODO: Port to django 1.10 and upward

    def __init__(self, get_response):
        """

        :param get_response:
        """
        self.get_response = get_response
        regex = ">[\s]*<"

    def __call__(self, request):
        """

        :param request:
        :return:
        """

        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        if 'text/html' in response['Content-Type']:
            response.content = strip_spaces_between_tags(
                response.content).strip()
        return response

class SetRemoteAddrFromForwardedFor(object):
    def process_request(self, request):
        try:
            real_ip = request.META['HTTP_X_FORWARDED_FOR']
            real_ip = real_ip.split(",")[0]
        except KeyError:
            pass
        else:
            # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
            # Take just the first one.
            request.META['REMOTE_ADDR'] = real_ip
