from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Group
from guardian.shortcuts import assign, remove_perm
from manager import SafeManager

def protect_models(user):
    for cls in get_models_to_protect():
            protect_model(cls, user)
    
def unprotect_models():
    for cls in get_models_to_protect():
            unprotect_model(cls)

def get_models_to_protect():        
    to_protect = []
        
    for cls_name in settings.USE_GROUP_PERMISSIONS:
        cls_type = ContentType.objects.get(app_label="ldt_utils", model=cls_name.lower())
        to_protect.append(cls_type.model_class())
    return to_protect

def protect_model(cls, user):
    cls.base_objects = cls.objects
    cls.objects = SafeManager(cls, user)
    
    cls.base_save = cls.save
    cls.save = change_security(user, cls.__name__.lower())(cls.save)
    
    
def unprotect_model(cls):    
    if hasattr(cls, 'base_objects'):
        cls.objects = cls.base_objects
        cls.save = cls.base_save
        del cls.base_objects    
        del cls.base_save
        
def change_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 is not allowed to change object %s' % (user, self))
            
            return func(self, *args, **kwargs)
        return wrapped    
    return wrapper

def assign_project_to_groups(project, permissions):
    for elem in permissions:
        group = Group.objects.get(id=elem['group'])
        if elem['share']:
            assign('view_project', group, project)
            if elem['perms'] == 'write':
                assign('change_project', group, project)
        else:
            remove_perm('view_project', group, project)
            remove_perm('change_project', group, project) 