from template_utils.templatetags.generic_markup import apply_markup, register
from template_utils.markup import formatter
from django.template import Library

def mm_markdown(text, **kwargs):
    """
    do some media trickery before applying markdown like parsing ![File:123]
    """
    import markdown
    from journalism_mm.tutorials.models import File
    import re

    # Fixup the source text
    text = text.strip()
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    text += "\n\n"

    # Split into lines and run the preprocessors that will work with
    # self.lines

    lines = text.split("\n")

    for i in range(len(lines)) :

        if lines[i].startswith('![File:'):
            try:
                f=File.objects.get(id=lines[i].replace(']','').split(':')[1])
            except File.DoesNotExist:
                lines[i]='<p>File Not Found</p>'
                pass
            else :
                if re.search('(\.gif|\.png|\.jpg|\.jpeg)', f.file):
                    lines[i]='<img src="/media/%s" title="%s" alt="%s" />' % (f.file, f.title, f.alt)
                else :
                    lines[i]='no mimetype match'
    text = '\n'.join(lines)
    return markdown.markdown(text, **kwargs)

formatter.register('mm_markdown',mm_markdown)