#
# Django-Lets-go License
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <info@star2billing.com>
#

from django import http


class FilterPersistMiddleware(object):

    def process_request(self, request):

        path = request.path
        if path.find('/admin/') != -1:  # Dont waste time if we aren't in admin
            query_string = request.META['QUERY_STRING']
            if not ('HTTP_REFERER' in request.META):
                return None

            session = request.session
            # so that we dont loop once redirected
            if session.get('redirected', False):
                del session['redirected']
                return None

            referrer = request.META['HTTP_REFERER'].split('?')[0]
            referrer = referrer[referrer.find('/admin'):len(referrer)]
            key = 'key' + path.replace('/', '_')

            if path == referrer:  # We are in same page as before
                if query_string == '':  # Filter is empty, delete it
                    if session.get(key, False):
                        del session[key]
                    return None
                request.session[key] = query_string
            else:  # coming from another page, restore filter if available
                if session.get(key, False):
                    query_string = request.session.get(key)
                    redirect_to = path + '?' + query_string
                    request.session['redirected'] = True
                    return http.HttpResponseRedirect(redirect_to)
                else:
                    return None
        else:
            return None
