from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from guardian.models import UserObjectPermission, GroupObjectPermission

import logging
logger = logging.getLogger(__name__)

def check_object_perm_for_user(obj, perm_name, user):
    # 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:
        logger.debug("COUCOU 5-2")
        uop = UserObjectPermission.objects.get(user=user, content_type=content_type, permission=perm, object_pk=obj.pk)
        logger.debug("COUCOU 5-3")
        if uop:
            logger.debug("COUCOU 5-4")
            can_change = True
        logger.debug("COUCOU 5-5")
    except:
        logger.debug("COUCOU 5-6")
        can_change = False
    logger.debug("COUCOU 5-7 can_change =")
    logger.debug(can_change)
    # Check for user's groups if necessary
    if not can_change:
        try:
            logger.debug("COUCOU G-2")
            gop = GroupObjectPermission.objects.filter(group__user=user, content_type=content_type, permission=perm, object_pk=obj.pk)
            logger.debug("COUCOU G-3")
            if gop and len(gop)>0:
                logger.debug("COUCOU G-4")
                can_change = True
            logger.debug("COUCOU G-5")
        except:
            logger.debug("COUCOU G-6")
            can_change = False
        logger.debug("COUCOU G-7 can_change =")
        logger.debug(can_change)
    # End
    return can_change
    