try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.4 fallback.
from django.shortcuts import redirect
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.decorators import available_attrs
from django.utils.cache import patch_cache_control
from django.views.decorators.cache import never_cache as old_never_cache

def no_delegate(view_func):
    '''
       Forbid delegated account to use this view.
    '''
    @wraps(view_func, assigned=available_attrs(view_func))
    def f(request, *args, **kwargs):
        if hasattr(request.user, 'delegate'):
            messages.warning(request, _('Your delegation does not allow you to do this action'))
            return redirect('inbox')
        return view_func(request, *args, **kwargs)
    return f


def as_delegate(view_func):
    '''
       Replace the effective user by the real user of the delegate for the
       given view.
    '''
    @wraps(view_func, assigned=available_attrs(view_func))
    def f(request, *args, **kwargs):
        if hasattr(request.user, 'delegate'):
            old_user = request.user
            request.user = request.user.delegate
            out = view_func(request, *args, **kwargs)
            request.user = old_user
            return out
        else:
            return view_func(request, *args, **kwargs)
    return f


def never_cache(view_func):
    '''Block client caching in all browsers.'''
    view_func = old_never_cache(view_func)
    @wraps(view_func, assigned=available_attrs(view_func))
    def f(request, *args, **kwargs):
        result = view_func(request, *args, **kwargs)
        patch_cache_control(result, no_cache=True)
        patch_cache_control(result, no_store=True)
        patch_cache_control(result, must_revalidate=True)
        return result
    return f
