from markdown import Markdown
from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE

from ..models import Image


class ImageLookupImagePattern(ImagePattern):

    def sanitize_url(self, url):
        if url.startswith("http"):
            return url
        else:
            try:
                image = Image.objects.get(pk=int(url))
                return image.image_path.url
            except Image.DoesNotExist:
                pass
            except ValueError:
                return url
        return ""


def parse(text):
    md = Markdown(extensions=["codehilite", "tables", "smarty", "admonition", "toc"])
    md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md)
    html = md.convert(text)
    return html

@@ -622,16 +622,31 @@
 %22, %22toc%22
+, %22fenced_code%22
 %5D)%0A    m

add support for fenced_code extension