from django.db.models import Manager
from guardian.shortcuts import get_objects_for_user
from ldt.security import get_current_user, get_anonymous_user

class SafeManager(Manager):
    use_for_related_fields = True
    
    def __init__(self, user=None, check_perm=False):
        super(SafeManager, self).__init__()
        self.user = user
        self.check_perm = check_perm

    def get_query_set(self):
        
        if not self.check_perm:
            return super(SafeManager, self).get_query_set()   
      
        if not self.user:
            self.user = get_current_user()            

        if not self.user:
            raise AttributeError("No user is attached to the current thread.")
        
        if not self.user.is_authenticated():
            self.user = get_anonymous_user()
        
        perm_name = '%s.view_%s' % (self.model._meta.app_label, self.model.__name__.lower()) 
        
        user_objects = get_objects_for_user(self.user, perm_name, klass=self.model.objects) 
                    
        return user_objects