from django import template
from django.utils.safestring import mark_safe
from django.urls import reverse_lazy
from django.template.defaultfilters import pluralize, linebreaks, urlize
from django.db.models import Q, F
import re
from datetime import date, timedelta, datetime

from agenda_culturel.models import Event
from django.db.models import Q

from .utils_extra import picto_from_name

register = template.Library()


@register.filter
def in_date(event, date):
    return event.filter(
        (Q(start_day__lte=date) & Q(end_day__gte=date))
        | (Q(end_day=None) & Q(start_day=date))
    )


@register.filter
def can_show_start_time(event, day=None):
    if day is not None and day == event.start_day:
        return True
    return event.start_time and (not event.end_day or event.end_day == event.start_day)


@register.filter
def can_show_end_time(event, day=None):
    if day is not None and day == event.end_day and event.start_day != event.end_day:
        return True
    return False


@register.filter
def need_complete_display(event, display_full=True):
    return (
        event.end_day
        and event.end_day != event.start_day
        and (event.start_time or event.end_time or display_full)
    )


@register.filter
def picto_status(event):
    if event.is_draft():
        return picto_from_name("eye-off", "Brouillon")
    elif event.is_trash():
        return picto_from_name("trash-2", "À la corbeille")
    else:
        return ""

@register.filter
def picto_visibility(event, visible=True):
    if not visible:
        return ""
    if event.is_representative():
        return picto_from_name("award")
    elif event.masked():
        return picto_from_name("archive")
    else:
        return ""


@register.simple_tag
def show_badge_moderate():
    first_day = datetime.now()
    start_day = first_day.date()
    start_time = first_day.time()
    last_day = start_day + timedelta(days=7)
    nb = Event.objects.filter(~Q(status=Event.STATUS.TRASH)). \
            filter(Q(start_day__lte=last_day)). \
            filter(Q(start_day__gt=start_day)|(Q(start_day=start_day) & (Q(start_time__isnull=True)|Q(start_time__gt=start_time)))). \
            filter(moderated_date__isnull=True). \
            filter(
                Q(other_versions__isnull=True) |
                Q(other_versions__representative=F('pk')) |
                Q(other_versions__representative__isnull=True)).values("start_day").\
            count()

    if nb == 0:
        return ""
    else:
        return mark_safe('<a href="' + reverse_lazy('moderate') + '" ' +
            ' data-placement="bottom" '
            ' data-tooltip="' + str(nb) + ' événements à modérer (7 jours)"' + 
            ' class="badge" aria-label="modérer">' + 
            picto_from_name("target") + ' ' + str(nb) + '</a>')


@register.simple_tag
def show_badges_events(placement="top"):
    nb_drafts = Event.nb_draft_events()
    if nb_drafts != 0:
        return mark_safe(
            '<a href="'
            + reverse_lazy("recent")
            + '?status=draft" class="badge" data-placement="'
            + placement
            + '" data-tooltip="'
            + str(nb_drafts)
            + " brouillon"
            + pluralize(nb_drafts)
            + ' à valider">'
            + picto_from_name("calendar")
            + " "
            + str(nb_drafts)
            + "</a>"
        )
    else:
        return ""


@register.simple_tag
def show_badge_unknown_places(placement="top"):
    nb_unknown = Event.get_qs_events_with_unkwnon_place().count()
    if nb_unknown != 0:
        return mark_safe(
            '<a href="'
            + reverse_lazy("view_unknown_places")
            + '" class="badge" data-placement="'
            + placement
            + '" data-tooltip="'
            + str(nb_unknown)
            + " événement"
            + pluralize(nb_unknown)
            + ' sans lieu défini">'
            + picto_from_name("map-pin")
            + " "
            + str(nb_unknown)
            + "</a>"
        )
    else:
        return ""


@register.simple_tag
def event_field_verbose_name(the_field):
    return Event._meta.get_field(the_field).verbose_name


@register.simple_tag
def field_to_html(field, key):
    if field is None:
        return "-"
    elif key == "description":
        return urlize(mark_safe(linebreaks(field)))
    elif key == "reference_urls":
        return mark_safe(
            "<ul>"
            + "".join(['<li><a href="' + u + '">' + u + "</a></li>" for u in field])
            + "</ul>"
        )
    elif key == "image":
        return mark_safe('<a href="' + field + '">' + field + "</a>")
    elif key == "local_image":
        if field:
            return mark_safe('<img class="preview" src="' + field.url + '" />')
        else:
            return "-"
    elif isinstance(field, list):
        if len(field) > 0:
            return mark_safe(
                "<ul>"
                + "".join(['<li>' + i + "</li>" for i in field])
                + "</ul>"
            )
        else:
            return mark_safe('<em>non renseigné</em>')
    else:
        return field


@register.filter
def add_url_category(url, c):
    if c is None:
        return url
    if url == "":
        return "category=" + str(c.pk)
    else:
        return url + "&category=" + str(c.pk)

@register.filter
def robust_urlize(txt):
    return mark_safe(urlize(mark_safe(txt.replace("http", " http"))).replace(" <a ", "<a "))

@register.filter
def linebreaks2(txt):
    res = linebreaks(txt)
    
    return mark_safe(re.sub("(<br> )+", "<br>", res))


@register.filter
def only_allowed(elist, is_authenticated):
    if not is_authenticated:
        return [e for e in elist if e.status == Event.STATUS.PUBLISHED]
    else:
        return elist

@register.filter
def tw_badge(event):
    if event.tags and len([t for t in event.tags if t.startswith("TW:")]) > 0:
        return mark_safe('<span class="badge tw-badge">TW</span>')
    else:
        return ""

@register.filter
def get_image_uri(event, request):
    return event.get_image_url(request)