from apps.comments.models.comment import Comment
from django import template
from django.contrib.contenttypes.models import ContentType
from mptt.templatetags.mptt_tags import cache_tree_children

register = template.Library()


@register.inclusion_tag('comments/comments_tree.html', takes_context=True)
def render_comments(context, target):
    content_type = ContentType.objects.get_for_model(target)
    comments = Comment.get_tree_list(content_type=content_type,
                                     object_id=target.id,
                                     is_public=True)
    # cached_comments = cache_tree_children(comments)
    comments_enabled = context.get('comments_enabled') and target.allow_comment

    return {
        'comments': comments,
        'target': target,
        'comments_enabled': comments_enabled,
        'user': context.get('user')
    }


@register.simple_tag
def get_comments_count(target):
    content_type = ContentType.objects.get_for_model(target)
    return Comment.objects.filter(content_type=content_type,
                                  object_id=target.id,
                                  is_public=True).count()


@register.filter
def get_content_type_id(obj):
    return ContentType.objects.get_for_model(obj).id
