from django.template import Library, TemplateSyntaxError

register = Library()

import logging
logger = logging.getLogger(__name__)

@register.filter
def get_tags(value, arg=None):
    """ Takes a segment's tag list and returns an array of values from argument. Example seg_obj|get_tags:"personnages" will return "Romeo, Juliette" """
    # Error management
    if value is None :
        return ""
    #if not isinstance(value, (str,unicode)) :
    #if not isinstance(value, (str,unicode)) :
    #    raise TemplateSyntaxError('get_tags value error : string is required')
    # If no arg, we join all values
    #a = value.split(u",")
    if isinstance(value, list):
        # Simple list of strings
        a = [t for t in value]
    else:
        # TaggableManager instance
        a = [t.name for t in value.all()]
    val = []
    if arg is None :
        for t in a:
            try:
                t.index(":")
            except:
                continue
            val.append(t[t.index(":")+2:])
    elif arg=="modscen_and_perso":
        for t in a:
            try:
                t.index(":")
            except:
                continue
            if t[:t.index(":")]=="modalites_sceniques" or t[:t.index(":")]=="personnages":
                val.append(t[t.index(":")+2:])
    elif arg in ["type_inter", "personnages", "ref_text", "opera_modalites_sceniques", "opera_personnages", "opera_type_travail", "opera_acte", "opera_scene", "opera_mesure"]:
        for t in a:
            try:
                t.index(":")
            except:
                continue
            if t[:t.index(":")]==arg:
                val.append(t[t.index(":")+2:])
    elif arg=="group":
        key_vals = {}
        for t in a:
            try:
                t.index(":")
            except:
                continue
            k = t[:t.index(":")]
            v = t[t.index(":")+2:]
            if k not in key_vals:
                key_vals[k] = []
            key_vals[k].append(v)
        output = ""
        for k,v in key_vals.items():
            if output != "":
                output += "<br/>"
            output += "<strong>" + k.capitalize() + "</strong>" + ": " + ", ".join(v)
        return output
             
    return val
get_tags.is_safe = True

@register.filter
def remove_tag_key(value):
    """ Takes a string as 'key: value' and returns the value """
    # Error management
    if value is None :
        return ""
    if not isinstance(value, (str,unicode)) :
        raise TemplateSyntaxError('remove_tag_key value error : string is required')
    try:
        value.index(":")
    except:
        return value
    return value[value.index(":")+2:]
remove_tag_key.is_safe = True

@register.filter
def remove_opera(value):
    """ Takes a string as 'opera_key: value' and returns the 'key: value' """
    # Error management
    if value is None :
        return ""
    if not isinstance(value, (str,unicode)) :
        raise TemplateSyntaxError('remove_tag_key value error : string is required')
    if value[:6]=="opera_":
        return value[6:]
    return value
remove_tag_key.is_safe = True

