# Django middleware to improve the admin site experience.
#
# I hate it that whenever I use the filters in django's admin to get to a
# selection of objects and then edit one of them, django sends me back to the
# unfiltered list. This small piece of middleware makes it remember the
# filters. It requires the admin interface to be 'mounted' as /admin/ but that
# can easily be changed below.
#
# When it's cached:
#  - Every time a filter is used on /admin/app/model/
# When is it used:
# - When coming back from an edit page
# When is it cleaned:
# - When navigating away
# - When clicking on a link in the list
#
# Copyright (c) 2009 Dennis Kaarsemaker <dennis@kaarsemaker.net>
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 
#     1. Redistributions of source code must retain the above copyright notice, 
#        this list of conditions and the following disclaimer.
#     
#     2. Redistributions in binary form must reproduce the above copyright 
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
# 
#     3. Neither the name of Django nor the names of its contributors may be used
#        to endorse or promote products derived from this software without
#        specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from django.core.cache import cache
from django.http import HttpResponseRedirect

class FilterCacheMiddleware(object):

    def process_request(self, request):
        """If needed, use cached query parameters"""
        # Use cached query parameters
        if request.startswith('/admin/') and request.path.count('/') == 4:
            # When seeing things in the cache with False as use_me, someone clicked a link
            ce = cache.get('filtercache:' + request.user.username)
            if ce and (ce[2] == False):
                cache.delete('filtercache:' + request.user.username)
            # If there are still things in the cache, use them
            elif ce and (ce[0] == request.path):
                cache.delete('filtercache:' + request.user.username)
                return HttpResponseRedirect('./?' + ce[1])

    def process_response(self, request, response):
        """Cache query parameters or clean cache"""

        # Don't care about errors
        if response.status_code != 200:
            return response

        # No action on non-admin pages
        if not request.path.startswith('/admin/') or not request.path.count('/') >= 4:
            return response
        # On an edit page, set the use_me field to True
        ce = cache.get('filtercache:' + request.user.username)
        if ce and (request.path.count('/') == 5) and request.path.startswith(ce[0]):
            ce[2] = True
            cache.set('filtercache:' + request.user.username, ce, 300)
        # Cache if on a list page and params given
        elif request.path.count('/') == 4 and request.GET.items():
            cache.set('filtercache:' + request.user.username, [request.path, request.META['QUERY_STRING'], False], 300)
        # Clean up on other pages
        elif ce:
            cache.delete('filtercache:' + request.user.username)

        return response

