import re

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

from ..utils import to_ukf

register = template.Library()

register.filter("ukf", to_ukf)


@register.filter()
def highlight_text(text, q):
    q2 = "|".join(re.escape(word) for word in q.split())
    pattern = re.compile(r"(?P<filter>%s)" % q2, re.IGNORECASE)
    regex = r"<span class='highlight_autocomplete'>\g<filter></span>"
    return mark_safe(re.sub(pattern, regex, escape(text)))


@register.filter(is_safe=True)
def highlight_user(user, q):
    if user.first_name and user.last_name:
        text = "%s %s (%s)" % (user.first_name, user.last_name, user.username)
    else:
        text = user.username
    return highlight_text(text, q)


@register.filter(is_safe=True)
def highlight_clipper(clipper, q):
    if clipper.fullname:
        text = "%s (%s)" % (clipper.fullname, clipper.clipper)
    else:
        text = clipper.clipper
    return highlight_text(text, q)


@register.filter()
def widget_type(field):
    return field.field.widget.__class__.__name__


@register.filter()
def slice(l, start, end=None):
    if end is None:
        end = start
        start = 0
    return l[start:end]
