from django.apps import apps
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType


def check_object_perm_for_user(obj, perm_name, user):
    # If user is admin...
    if user.is_staff or user.is_superuser:
        return True
    # Guardian has_perm request is REALLY long and not optimized.
    # So we check manually the change_project permission for the user and the user's groups
    # Get necessary datas
    model_name = obj.__class__.__name__.lower()
    content_type = ContentType.objects.get(model=model_name)
    perm = Permission.objects.get(codename=perm_name)
    can_change = False
    # Check for the user
    try:
        UserObjectPermission = apps.get_model('guardian.UserObjectPermission')
        uop = UserObjectPermission.objects.get(user=user, content_type=content_type, permission=perm, object_pk=obj.pk)
        if uop:
            can_change = True
    except:
        can_change = False
    # Check for user's groups if necessary
    if not can_change:
        try:
            GroupObjectPermission = apps.get_model('guardian.GroupObjectPermission')
            gop = GroupObjectPermission.objects.filter(group__user=user, content_type=content_type, permission=perm, object_pk=obj.pk)
            if gop and len(gop)>0:
                can_change = True
        except:
            can_change = False
    # End
    return can_change
