import bbcode
from . import formatters
from ... import settings
PARSER = bbcode.Parser(newline="\n",escape_html=True,replace_links=False)

def _():
    from django.utils.module_loading import import_string

    def add_simple_formatters(simple_formatters):
        for i in simple_formatters:
            if len(i) == 0:
                continue

            if len(i) == 1:
                kwargs = {}
            else:
                kwargs = i[1]
        PARSER.add_simple_formatter(*i[0], **kwargs)

    def add_formatters(formatters):
        for i in formatters:

            if len(i) == 0:
                continue

            if isinstance(i[0][1], str):
                if len(i[0]) < 2:
                    continue
                elif len(i[0]) == 2:
                    args = (i[0][0], import_string(i[0][1]))
                else:
                    args = (i[0][0], import_string(i[0][1]), *i[2:])
            else:
                args = i[0]

            if len(i) == 1:
                kwargs = {}
            else:
                kwargs = i[1]

            PARSER.add_formatter(*args, **kwargs)

    add_simple_formatters(formatters.SIMPLE_FORMATTERS)
    add_formatters(formatters.FORMATTERS)
    if settings.TINYWIKI_BBCODE_EXTR_SIMPLE_FORMATTERS:
        add_simple_formatters(settings.TINYWIKI_BBCODE_EXTR_SIMPLE_FORMATTERS)
    if settings.TINYWIKI_BBCODE_EXTRA_FORMATTERS:
        add_formatters(settings.TINYWIKI_BBCODE_EXTRA_FORMATTERS)

_()
del _