from django import template
from django.db.models.aggregates import Count
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

import markdown

from ..models import Post, Category, Tag

register = template.Library()

@register.simple_tag
def get_recent_posts(num=5):
    return Post.objects.filter(access_level='public').order_by('-created_time')[:num]

@register.simple_tag
def get_categories():
    return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)

@register.simple_tag
def get_tags():
    return Tag.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)

@register.simple_tag
def get_archives():
    return Post.objects.dates('created_time', 'month', order='DESC')

@register.filter(is_safe=True)
@stringfilter
def mymarkdown(content):
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        'markdown.extensions.fenced_code',
    ])
    return md.convert(content)