from django.db.models import Manager
from guardian.core import ObjectPermissionChecker
from guardian.shortcuts import get_objects_for_user

class SafeManager(Manager):
    
    def __init__(self, cls, user=None):
        super(SafeManager, self).__init__()
        self.model_name = cls.__name__.lower()
        self.model = cls  
        if user:
            self.check_perm_for(user)
        else:
            self.user = None
            self.checker = None     
    
    def check_perm_for(self, user):
        self.user = user
        self.checker = ObjectPermissionChecker(self.user)
        
    def stop_checking(self):
        self.user = None
        self.checker = None
      
    def has_user(self):
        return self.user != None        
      
    def get_query_set(self):
        if not self.has_user():
            raise AttributeError("A user has to be chosen to check permissions.")
        
        user_objects = get_objects_for_user(self.user, 'ldt_utils.view_%s' % self.model_name)
            
        return user_objects 