from django.template import Library
from django.template.defaultfilters import stringfilter
from django.utils.safestring import SafeData

register = Library()


@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def reduce(value, nbs, autoescape=None):
    """
    Replace a string by "..." and its last characters. Usefull to display strings where end matters
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    # nbs is "nb_char_start,nb_char_end"
    a = nbs.split(",")
    nb_start = int(a[0])
    nb_end = int(a[1])
    return value[:nb_start] + "..." + value[-nb_end:]
