# -*- coding: utf-8 -*-

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

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

import re

register = template.Library()


@register.filter
def key(d, key_name):
    try:
        value = d[key_name]
    except KeyError:
        from django.conf import settings
        value = settings.TEMPLATE_STRING_IF_INVALID
    return value


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)
    return mark_safe(re.sub(pattern,
                            r"<span class='highlight'>\g<filter></span>",
                            text))


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


@register.filter
def highlight_clipper(clipper, q):
    if clipper.fullname:
        text = "%s (<tt>%s</tt>)" % (clipper.fullname, clipper.clipper)
    else:
        text = clipper.clipper
    return highlight_text(text, q)
