from django.conf import settings
from django.db.models import Manager
from models import Project
from guardian.core import ObjectPermissionChecker
from guardian.shortcuts import get_objects_for_user, assign

VERSION = (0, 1)
VERSION_STR = unicode(".".join(map(lambda i:"%02d" % (i,), VERSION)))

def protect_class(cls, user):
    cls.base_objects = cls.objects
    cls.objects = SafeManager(cls, user)
    
    cls.base_save = cls.save
    cls.save = save_security(user, cls.__name__.lower())(cls.save)
    
def unprotect_class(cls):
    
    if hasattr(Project, 'base_objects'):
        cls.objects = cls.base_objects
        cls.save = cls.base_save
        del cls.base_objects    
        del cls.base_save

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_projects = get_objects_for_user(self.user, 'ldt_utils.view_%s' % self.model_name)
            
        return user_projects
    
    
def save_security(user, cls_name):
    def wrapper(func):
        def wrapped(self, *args, **kwargs):
            
            if self.pk and not user.has_perm('change_%s' % cls_name, 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

    
    