from __future__ import absolute_import

from django import template
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_permission_codename

from passerelle.utils import get_trusted_services
from ..models import AccessRight

register = template.Library()

@register.inclusion_tag('passerelle/includes/access-rights-table.html', takes_context=True)
def access_rights_table(context, resource, permission):
    resource_type = ContentType.objects.get_for_model(resource)
    rights = AccessRight.objects.filter(resource_type=resource_type,
            resource_pk=resource.id, codename=permission)
    context['permission'] = permission
    context['access_rights_list'] = rights
    context['resource_type'] = resource_type.id
    context['resource_pk'] = resource.id
    context['trusted_services'] = get_trusted_services()
    return context


@register.filter
def can_edit(obj, user):
    return user.has_perm(get_permission_codename('change', obj._meta), obj=obj)


@register.filter
def can_delete(obj, user):
    return user.has_perm(get_permission_codename('delete', obj._meta), obj=obj)
