__license__ = "Python"
__copyright__ = "Copyright (C) 2007, Stephen Zabel"
__author__ = "Stephen Zabel - sjzabel@gmail.com"


from django.conf import settings
from django.http import HttpResponseRedirect, get_host

APPENDSLASH = 'AppendSlash'
DEFAULTBEHAVIOR = settings.APPENDSLASH_DEFAULTBEHAVIOR and settings.APPENDSLASH_DEFAULTBEHAVIOR or True

class AppendSlashRedirect:
    def process_view(self, request, view_func, view_args, view_kwargs):
        if SSL in view_kwargs:
            append = view_kwargs[APPENDSLASH]
            del view_kwargs[APPENDSLASH]
        else:
            append = DEFAULTBEHAVIOR

        if not append == request.path[-1] != '/':
            return self._redirect(request, append)

    def _redirect(self, request, append):
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, \
"""You can't perform a redirect while maintaining POST data.
Please structure your views so that redirects only occur during GETs."""

        d = {}
        d['protocol'] = request.is_secure() and 'https' or 'http'
        d['host'] = request.get_host(request)
        d['path'] = append and request.path()+"/" or request.path()[:-1]
        d['parms'] = request.GET and '?' + request.GET.urlencode() or ''

        newurl = "%(protocol)s://%(host)s%(path)s%(parms)s" % d

        return HttpResponsePermanentRedirect(newurl)