"""Safe rendering for the company 'About' text: paragraphs, simple headings and bullet lists."""
import re

from django import template
from django.template.defaultfilters import urlize
from django.utils.html import escape
from django.utils.safestring import mark_safe

register = template.Library()

_HEADING = re.compile(r'^#{1,3}\s+(.+?)\s*#*\s*$')
_BULLET = re.compile(r'^\s*[-*•]\s+(.+?)\s*$')


def _inline(text):
    html = urlize(escape(text), autoescape=False)
    return re.sub(r'<a ', '<a target="_blank" rel="noopener noreferrer" ', str(html))


@register.filter
def company_html(value):
    if not value:
        return ''
    out, para, items = [], [], []

    def flush_para():
        if para:
            out.append('<p>%s</p>' % _inline(' '.join(para)))
            para.clear()

    def flush_list():
        if items:
            out.append('<ul class="company-about-list">%s</ul>' % ''.join('<li>%s</li>' % _inline(i) for i in items))
            items.clear()

    for raw in str(value).replace('\r\n', '\n').replace('\r', '\n').split('\n'):
        line = raw.replace('\xa0', ' ').strip()
        if not line:
            flush_para()
            flush_list()
            continue
        heading = _HEADING.match(line)
        bullet = _BULLET.match(line)
        if heading:
            flush_para()
            flush_list()
            out.append('<h3 class="company-about-heading">%s</h3>' % escape(heading.group(1)))
        elif bullet:
            flush_para()
            items.append(bullet.group(1))
        else:
            flush_list()
            para.append(line)
    flush_para()
    flush_list()
    return mark_safe(''.join(out))
