from django import template
from django.utils.safestring import mark_safe
from django.urls import reverse_lazy
from agenda_culturel.models import Tag
from .utils_extra import *
from .cat_extra import *

register = template.Library()


def t_button(tag, url, strike=False, category=None):
    strike_class = " strike" if strike else ""
    cat = "" if category is None else circle_cat(category) + ' ' 
    if not url is None:
        return mark_safe(
            '<a href="'
            + url
            + '" role="button" class="small-cat'
            + strike_class
            + '">'
            + cat 
            + tag
            + "</a>"
        )
    else:
        return mark_safe(
            '<span role="button" class="small-cat'
            + strike_class
            + '">'
            + cat 
            + tag
            + "</span>"
        )

@register.filter
def tag_button(tag, link=False, strike=False):
    return t_button(tag, reverse_lazy("view_tag", kwargs={"t": tag.replace('/', '-')}) if link else None, strike)


@register.filter
def tag_button_strike(tag, link=False):
    return tag_button(tag, link, strike=True)

@register.filter
def tag_button_link(tag):
    return t_button(tag, '/?tags=' + tag, False)

@register.filter
def tag_not_in_db(tag, tags):
    return len([t for t in tags if t.name == tag]) == 0


@register.simple_tag
def show_suggested_tags(filter):
    filter.form.full_clean()
    tags = Tag.objects.all().filter(principal=True).order_by("name")
    result = ""

    for t in tags:
        if filter.tag_exists(t.name) and not filter.is_selected_tag(t.name):
            result += ' ' + t_button(t.name, filter.get_url_add_tag(t.name))

    return mark_safe(result)

@register.filter
def prepare_tag(tag):
    return tag.replace('/', '-')

@register.filter
def tw_highlight(tag):
    if tag.startswith('TW:'):
        return mark_safe('<span class="tw-prefix">TW:</span>' + tag[3:])
    else:
        return tag