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
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


@app.template_filter('md')
def md(text):
    """
    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),
        PCLinkExtension(),
    ]

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

    return Markup(out)
