from django.template import Library
from django.template.defaultfilters import stringfilter
from utils.utils import set_trace

register = Library()

@register.filter
def pretty_name(user):
    res = ''
    if user.first_name:
        res = user.first_name
        if user.last_name:
            res += ' ' + user.last_name
    elif user.username and not user.username.lower().startswith('http') and not user.username.isalnum():
        res = user.username
    elif user.email:
        res = user.email
    else:
        res = 'User%s' % str(user.id)
    if res.find('@') > 0: #looks like an email
        res = res[:res.find('@')]
    return res
pretty_name.is_safe = True


@register.filter(name='truncatechars')
def truncatechars(value, arg):
    """
    Truncates a string after a certain number of chars.

    Argument: Number of chars to truncate after.
    """
    try:
        length = int(arg)
    except ValueError: # Invalid literal for int().
        return value # Fail silently.
    if len(value) > length:
        return value[:length] + '...'
    return value
truncatechars.is_safe = True


