import pytest
from django.test import signals
from django.test.client import Client
from django.contrib.auth.models import User, Permission
from jinja2 import Template as Jinja2Template


## Wait for https://code.djangoproject.com/ticket/24622


ORIGINAL_JINJA2_RENDERER = Jinja2Template.render


def instrumented_render(template_object, *args, **kwargs):
    context = dict(*args, **kwargs)
    if 'request' in context:
        context['user'] = context['request'].user
    signals.template_rendered.send(
        sender=template_object,
        template=template_object,
        context=context
    )
    return ORIGINAL_JINJA2_RENDERER(template_object, *args, **kwargs)


@pytest.fixture(scope="module")
def context(request):
    Jinja2Template.render = instrumented_render

    def fin():
        Jinja2Template.render = ORIGINAL_JINJA2_RENDERER

    request.addfinalizer(fin)
    return None  # provide nothing


@pytest.fixture()
def user(db):
    user = User.objects.create_user('boubou', 'bou@bou.com', 'pass')
    return user


@pytest.fixture()
def user_client(db):
    client = Client()
    user = User.objects.create_user('boubou', 'bou@bou.com', 'pass')
    client.login(username='bou@bou.com', password='pass')
    client.user = user
    return client


@pytest.fixture()
def ivy_admin_client(db):
    client = Client()
    user = User.objects.create_user('boubouadmin', 'bouadmin@bou.com', 'pass')
    user.user_permissions.add(Permission.objects.get(codename='change_admin'))
    client.login(username='bouadmin@bou.com', password='pass')
    client.user = user
    return client
