import re

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.conf import settings

from preferences import preferences


class VerboseRequestMeta:
    """Add metadata to request so repr(request) prints more information. Runs
    as one of the last middleware."""

    def process_request(self, request):
        user = getattr(request, 'user', None)
        if user is not None:
            request.META['AUTHENTICATED_USER'] = str(user)


class AgeGateway:
    """Redirect if age gateway is enabled and user is anonymous. Must run after
    AuthenticationMiddleware."""

    def process_response(self, request, response):
        # Ignore ajax
        if request.is_ajax():
            return response

        # Already passed gateway
        if request.COOKIES.get('age_gateway_passed'):
            return response

        exempted_urls = (
            reverse('age-gateway'), reverse('join'), reverse('login'), 
            '/password_reset', '/static', '/admin'
        )

        # On an exempted url
        if re.match(r'|'.join(exempted_urls), request.META['PATH_INFO']) is not None:
            return response

        user = getattr(request, 'user', None)
        # xxx: investigate preference caching
        if (user is not None) and user.is_anonymous() and preferences.GeneralPreferences.show_age_gateway:
            return HttpResponseRedirect(exempted_urls[0])

        return response            


class PaginationMiddleware:
    """Our replacement for django-pagination PaginationMiddleware. It defaults
    to the last page if no page is set on the request. A monkey patch in
    monkey.py handles the negative page number."""

    def process_request(self, request):       
        page = -1
        try:
            page = int(request.REQUEST['page'])
        except (KeyError, ValueError, TypeError):
            pass
        request.__class__.page = page

@@ -166,16 +166,166 @@
 ences%0A%0A%0A
+PROTECTED_URLS = (%0A    reverse('age-gateway'), %0A    reverse('join'), %0A    reverse('login'), %0A    '/password_reset', %0A    '/static', %0A    '/admin'%0A)%0A%0A%0A
 class Ve
@@ -1027,157 +1027,452 @@
     
-exempted_urls = (%0A            reverse('age-gateway'), reverse('join'), reverse('login'), %0A            '/password_reset', '/static', '/admin'%0A
+# Protected URLs%0A        if re.match(r'%7C'.join(PROTECTED_URLS), request.META%5B'PATH_INFO'%5D) is not None:%0A            return response%0A%0A        # Now only do we hit the database%0A        # xxx: investigate preference caching. May want to hit the db less.%0A        if not preferences.GeneralPreferences.show_age_gateway:%0A            return response%0A%0A        # Exempted URLs%0A        exempted_urls = preferences.GeneralPreferences.exempted_urls
         
 )%0A%0A 
@@ -1467,18 +1467,16 @@
         
-)%0A
 %0A       
@@ -1480,15 +1480,10 @@
     
-# On an
+if
  exe
@@ -1491,12 +1491,15 @@
 pted
- 
+_
 url
+s %5C
 %0A   
@@ -1507,313 +1507,382 @@
     
-if re.match(r'%7C'.join(exempted_urls), request.META%5B'PATH_INFO'%5D) is not None:%0A            return response%0A%0A        user = getattr(request, 'user', None)%0A        # xxx: investigate preference caching%0A        if (user is not None) and user.is_anonymous() and preferences.GeneralPreferences.show_age_gateway:
+    and (%0A                re.match(%0A                    r'%7C'.join(exempted_urls.split()), %0A                    request.META%5B'PATH_INFO'%5D%0A               ) is not None%0A            ):%0A            return response%0A%0A        user = getattr(request, 'user', None)%0A        if (user is not None) and user.is_anonymous():%0A            # Redirect to age gateway (the first protected url)
 %0A   
@@ -1918,29 +1918,30 @@
 edirect(
-exempted_urls
+PROTECTED_URLS
 %5B0%5D)%0A%0A  

Implement exempted urls for age gateway