from django.db import models
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType

class PermissionManager(models.Manager):

    def get_content_type(self, obj):
        return ContentType.objects.get_for_model(obj)

    def get_for_model(self, obj):
        return self.filter(content_type=self.get_content_type(obj))

    def for_object(self, obj):
        return self.get_for_model(obj).select_related(
            'user', 'creator', 'group', 'content_type'
        ).filter(object_id=obj.id)

    def for_user(self, user, obj, check_groups=True):
        perms = self.get_for_model(obj)
        if not check_groups:
            return perms.select_related('user', 'creator').filter(user=user)
        return perms.select_related('user', 'user__groups', 'creator').filter(
            Q(user=user) | Q(group__in=user.groups.all()))

    def user_permissions(self, user, perm, obj, check_groups=True):
        return self.for_user(user, obj, check_groups).filter(codename=perm)

    def group_permissions(self, group, perm, obj):
        """
        Get objects that have Group perm permission on
        """
        return self.get_for_model(obj).select_related(
            'user', 'group', 'creator').filter(group=group, codename=perm)

    def delete_objects_permissions(self, obj):
        """
        Delete permissions related to an object instance
        """
        perms = self.for_object(obj)
        perms.delete()

    def delete_user_permissions(self, user, perm, obj, check_groups=False):
        """
        Remove granular permission perm from user on an object instance
        """
        user_perms = self.user_permissions(user, perm, obj, check_groups=False)
        if not user_perms.filter(object_id=obj.id):
            return
        perms = self.user_permissions(user, perm, obj).filter(object_id=obj.id)
        perms.delete()
