import datetime

import json
from django.utils.html import escape
from django.template.response import TemplateResponse
from django.utils.numberformat import format as nformat
from django.urls import reverse
from django.contrib.staticfiles.storage import staticfiles_storage

from jinja2 import Environment, PackageLoader


def to_json(value):
    return json.dumps(value, indent=2, ensure_ascii=False)


def human_delta(delta):
    if delta is None:
        return None

    if not isinstance(delta, datetime.timedelta):
        delta = datetime.timedelta(seconds=delta)

    return str(delta)


def intformat(value):
    if isinstance(value, (int, float)):
        return nformat(value, ',', 0, 3, ' ', True)
    else:
        return value


def custom_url(view, *args, **kwargs):
    return escape(reverse(view, args=args or None, kwargs=kwargs or None))


def environment(**options):
    options['loader'] = PackageLoader('intranet.search.admin', 'templates')
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': custom_url,
        'intformat': intformat,
        'human_delta': human_delta,
        'now': datetime.datetime.now,
    })
    env.filters.update({
        'to_json': to_json,
    })
    return env


def render(request, template, context, content_type='text/html', **kwargs):
    return TemplateResponse(request, template, context=context, content_type=content_type, **kwargs)
