from app import app
from markupsafe import Markup
from markdown import markdown
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.extensions.footnotes import FootnoteExtension
from markdown.extensions.toc import TocExtension, slugify_unicode
from bleach import clean
from app.utils.bleach_allowlist import markdown_tags, markdown_attrs

from app.utils.markdown_extensions.pclinks import PCLinkExtension
from app.utils.markdown_extensions.hardbreaks import HardBreakExtension
from app.utils.markdown_extensions.escape_html import EscapeHtmlExtension
from app.utils.markdown_extensions.linkify import LinkifyExtension
from app.utils.markdown_extensions.media import MediaExtension
from app.utils.markdown_extensions.gallery import GalleryExtension


def slug(prefix, text, sep):
    if prefix is None:
        return slugify_unicode(text, sep)
    else:
        return str(prefix) + sep + slugify_unicode(text, sep)

@app.template_filter('md')
def md(text, prefix=None):
    """
    Converts markdown to html5
    """

    options = 0
    extensions = [
        # 'admonition',
        'fenced_code',
        # 'nl2br',
        'sane_lists',
        'tables',
        CodeHiliteExtension(linenums=True, use_pygments=True),
        EscapeHtmlExtension(),
        FootnoteExtension(UNIQUE_IDS=True),
        HardBreakExtension(),
        LinkifyExtension(),
        TocExtension(baselevel=2, slugify=lambda *args: slug(prefix, *args)),
        PCLinkExtension(),
        MediaExtension(),
        GalleryExtension(),
    ]

    html = markdown(text, options=options, extensions=extensions)
    out = clean(html, markdown_tags, markdown_attrs)

    return Markup(out)
