"""Jinja2 environment: helpers and filters available in every template."""
from django.templatetags.static import static
from django.urls import reverse
from django.utils import timezone
from django.utils.timesince import timesince
from jinja2 import Environment

from crm.constants import KIND_LABELS, OUTCOME_LABELS, PRIORITY_LABELS, STAGE_LABELS


def _dt(v, fmt="%d %b %Y, %H:%M"):
    if not v:
        return "-"
    return timezone.localtime(v).strftime(fmt) if hasattr(v, "hour") else v.strftime("%d %b %Y")


def _label(k):
    if k.startswith("class_"):
        return "Class " + k[6:]
    import re
    return re.sub(r"([a-z])([A-Z])", r"\1 \2", k).replace("_", " ").capitalize()


def environment(**options):
    env = Environment(**options)
    env.globals.update({"static": static, "url": reverse, "STAGE_LABELS": STAGE_LABELS,
                        "PRIORITY_LABELS": PRIORITY_LABELS, "KIND_LABELS": KIND_LABELS,
                        "OUTCOME_LABELS": OUTCOME_LABELS})
    env.filters["dt"] = _dt
    env.filters["ago"] = lambda v: (timesince(v) + " ago") if v else "never"
    env.filters["label"] = _label
    env.filters["num"] = lambda v: "{:,}".format(int(v)) if v not in (None, "") else "-"
    return env
