from django import template
from django.utils.safestring import mark_safe
from django.urls import reverse_lazy
from django.template.defaultfilters import pluralize
from django.db.models import OuterRef, Subquery, Count


from agenda_culturel.models import RecurrentImport, BatchImportation

from .utils_extra import picto_from_name

register = template.Library()

import logging

logger = logging.getLogger(__name__)


def badge_rimport(status, nb, suffix, picto, cl, placement):
    return ('<a href="' 
        + reverse_lazy("recurrent_imports_status", args=[status])
        + '" class="badge ' + cl + '" data-placement="'
        + placement
        + '" data-tooltip="'
        + str(nb)
        + " importation"
        + pluralize(nb)
        + " récurrente"
        + pluralize(nb)
        + ' ' + suffix + '">'
        + picto_from_name(picto)
        + " "
        + str(nb)
        + "</a>")

@register.simple_tag
def show_badges_rimports(placement):
    newest = BatchImportation.objects.filter(recurrentImport=OuterRef("pk")).order_by(
        "-created_date"
    )
    request = RecurrentImport.objects.annotate(
            last_run_status=Subquery(newest.values("status")[:1])
        ).values("last_run_status").annotate(nb_last_run_by_status=Count("last_run_status"))


    nbs = {}
    for res in request:
        nbs[res["last_run_status"]] = res["nb_last_run_by_status"]

    result = ""

    for status in ["failed", "running"]:
        if status in nbs and nbs[status] != 0:
            if status == "failed":
                suffix = 'en erreur'
                picto = "alert-triangle"
                cl    = "error"
            else:
                suffix = ' en cours'
                picto = "refresh-cw"
                cl    = "simple"
            result += badge_rimport(status, nbs[status], suffix, picto, cl, placement)

    return mark_safe(result)
