from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
import markdown as md
from . import think_markdown
from . import tasklist_markdown

register = template.Library()

@register.filter()
@stringfilter
def markdown(value):
    """
    Basic markdown filter without task list support.
    Use markdown_with_tasks template tag for content with task states.
    """
    return mark_safe(md.markdown(value, extensions=['markdown.extensions.fenced_code',
                                        'markdown.extensions.tables',
                                        'markdown.extensions.nl2br',
                                        'markdown.extensions.toc',
                                        think_markdown.ThinkExtension()]))


@register.simple_tag
def markdown_with_tasks(content, task_states=None):
    """
    Render markdown with interactive task list support.

    Usage in template:
        {% markdown_with_tasks post.content post.task_states %}
    """
    if task_states is None:
        task_states = {}

    return mark_safe(md.markdown(
        content,
        extensions=[
            'markdown.extensions.fenced_code',
            'markdown.extensions.tables',
            'markdown.extensions.nl2br',
            'markdown.extensions.toc',
            think_markdown.ThinkExtension(),
            tasklist_markdown.TaskListExtension(task_states=task_states)
        ]
    ))
