import django_webtest
import pytest
from django.contrib.auth.models import User


class PublikTestResponse(django_webtest.DjangoWebtestResponse):
    @property
    def forms(self):
        # forms is a dict which allows access to forms by index or id, it looks like
        # {0: <Form id=None>, 1: <Form id="logout-form">, 2: <Form id=None>, "logout-form": <Form id="logout-form">}
        forms = super().forms

        # forbid access to logout form by index, forms should look like
        # {0: <Form id=None>, 1: <Form id=None>, "logout-form": <Form id="logout-form">}
        removed_logout_form = False
        for id_, form in forms.copy().items():
            if not isinstance(id_, int):
                continue

            if form.id == 'logout-form':
                del forms[id_]
                removed_logout_form = True
                continue

            if removed_logout_form:
                forms[id_ - 1] = forms.pop(id_)

        return forms


django_webtest.DjangoTestApp.response_class = PublikTestResponse


@pytest.fixture
def app(request):
    wtm = django_webtest.WebTestMixin()
    wtm.setup_auth = False
    wtm._patch_settings()
    request.addfinalizer(wtm._unpatch_settings)
    return django_webtest.DjangoTestApp()


@pytest.fixture
def admin_user():
    try:
        user = User.objects.get(username='admin')
    except User.DoesNotExist:
        user = User.objects.create_superuser('admin', email=None, password='admin')
    return user
