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

from p4l.utils import strip_accents


register = Library()


@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def reduce(value, nbs, autoescape=None):  # @ReservedAssignment
    """
    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:]

@register.filter(is_safe=True, name="strip_accents")
@stringfilter
def strip_accents_filter(value):
    """
    Strip accent from string
    """
    return strip_accents(value)