from django.conf import settings
from ldt.ldt_utils.models import Project


def group_security(func):
    def wrapper(request, *args, **kwargs):
        if settings.USE_GROUP_PERMISSIONS:
            if not request.user:
                raise AttributeError("A user should be set in the request.")
            
            if Project.objects_safe.has_user():
                response = func(request, *args, **kwargs)
            else:                    
                Project.objects_safe.check_perm_for(request.user)
                
                old_project_manager = Project.objects                         
                old_save_method = Project.save
                Project.save = save_security(request.user)(Project.save)
                Project.objects = Project.objects_safe
                
                response = func(request, *args, **kwargs)
                
                Project.objects = old_project_manager 
                Project.save = old_save_method     
                Project.objects_safe.stop_checking()
            
        else:
            response = func(request, *args, **kwargs)
        return response
    return wrapper

 
def save_security(user):
    def wrapper(func):
        def wrapped(self, *args, **kwargs):
            
            if not user.has_perm('change_project', self):
                raise AttributeError('User %s does not have sufficient permissions to change object %s' % (user, self))
            
            return func(self, *args, **kwargs)
        return wrapped
    return wrapper