from django import template
from django.utils.html import strip_tags
from blog.models import Comment
import html


register = template.Library()


@register.filter
def clean_html(value):
    """Удаляет HTML-теги и заменяет сущности на символы."""
    # Декодируем HTML-сущности (например, &nbsp; → пробел)
    value = html.unescape(value)
    # Удаляем все HTML-теги
    return strip_tags(value)


@register.inclusion_tag('blog/includes/comment_tree.html', takes_context=True)
def show_comments(context, comments, depth=0):
    request = context.get('request')
    user = request.user if request and request.user.is_authenticated else None

    filtered = []
    for c in comments:
        if c.is_moderated:
            filtered.append(c)
        elif user and c.user == user:
            filtered.append(c)

    return {
        'comments': filtered,
        'depth': depth,
        'user': user
    }