from django import template

from ..registry import kind_of
from ..stats import comments, summary

register = template.Library()


@register.inclusion_tag('engage/_bar.html', takes_context=True)
def engage(context, obj, title=''):
    request = context.get('request')
    user = getattr(request, 'user', None)
    kind = kind_of(obj)
    return {
        'obj': obj, 'kind': kind, 'title': title, 'request': request, 'user': user,
        's': summary(obj, user), 'comments': comments(obj), 'stars': range(1, 6),
        'csrf_token': context.get('csrf_token'),
    }


@register.simple_tag
def engage_schema(obj, rating=True):
    """JSON-LD fields for reader activity, ending with a comma (or empty):
    commentCount, interactionStatistic (likes, comments) and, when wanted, aggregateRating."""
    import json

    from django.utils.safestring import mark_safe

    from ..stats import aggregate_rating_schema, summary
    s = summary(obj)
    stats = []
    if s['likes']:
        stats.append({'@type': 'InteractionCounter', 'interactionType': 'https://schema.org/LikeAction',
                      'userInteractionCount': s['likes']})
    if s['comment_count']:
        stats.append({'@type': 'InteractionCounter', 'interactionType': 'https://schema.org/CommentAction',
                      'userInteractionCount': s['comment_count']})
    parts = {}
    if s['comment_count']:
        parts['commentCount'] = s['comment_count']
    if stats:
        parts['interactionStatistic'] = stats
    agg = aggregate_rating_schema(obj) if rating else None
    if agg:
        parts['aggregateRating'] = agg
    if not parts:
        return ''
    body = json.dumps(parts, ensure_ascii=False)[1:-1].replace('<', '\\u003c')
    return mark_safe(body + ',')
