# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations

import http

from django.test import Client
from django.urls import reverse
import pytest
from pytest_django import asserts


def assert_default_mode_response_context(response, access_tokens):
    expected_access_token_ids = list(sorted(
        [obj.pk for obj in access_tokens],
        reverse=True,
    ))

    assert len(response.context['access_tokens']) == 2
    assert response.context['access_tokens'][0].pk == expected_access_token_ids[0]
    assert response.context['access_tokens'][1].pk == expected_access_token_ids[1]
    assert response.context['before'] is None
    assert response.context['next_url'] is None


@pytest.mark.django_db
def test_ok(browsable_access_token_outs,
            authenticated_client: Client,
            ):
    # When
    result = authenticated_client.get(
        reverse('ui.accounts.apps.browse'),
    )

    # Then
    assert result.status_code == http.HTTPStatus.OK

    asserts.assertTemplateUsed(result, 'ui/accounts/apps/browse.html')

    assert_default_mode_response_context(result, browsable_access_token_outs)


@pytest.mark.django_db
def test_ok_htmx(browsable_access_token_outs,
                 authenticated_client: Client,
                 ):
    # When
    result = authenticated_client.get(
        reverse('ui.accounts.apps.browse'),
        headers={
            'HX-Request': 'true',
        },
    )

    # Then
    assert result.status_code == http.HTTPStatus.OK

    asserts.assertTemplateNotUsed(result, 'ui/accounts/apps/browse.html')
    asserts.assertTemplateUsed(result, 'ui/accounts/partials/apps/apps.html')

    assert_default_mode_response_context(result, browsable_access_token_outs)


@pytest.mark.parametrize(
    'query_before_index,expected_before_index,expected_length,first_index,last_index',
    [
        (None, 9, 10, 0, 9),
        (9, None, 2, 10, 11),
    ],
)
@pytest.mark.django_db
def test_pagination(query_before_index,
                    expected_before_index,
                    expected_length,
                    first_index,
                    last_index,
                    paginatable_access_token_outs,
                    authenticated_client: Client,
                    ):
    # Given
    request_data = {}

    if query_before_index is not None:
        request_data['before'] = str(
            paginatable_access_token_outs[query_before_index].pk,
        )

    # When
    result = authenticated_client.get(
        reverse('ui.accounts.apps.browse'),
        data=request_data,
    )

    # Then
    assert result.status_code == http.HTTPStatus.OK

    expected_before = None
    expected_next_url = None

    if expected_before_index:
        expected_before = paginatable_access_token_outs[expected_before_index].pk
        expected_next_url = reverse(
            'ui.accounts.apps.browse',
            query=[
                ('before', expected_before),
                ('limit', 10),
            ],
        )

    assert len(result.context['access_tokens']) == expected_length
    assert result.context['access_tokens'][0].pk == paginatable_access_token_outs[first_index].pk
    assert result.context['access_tokens'][-1].pk == paginatable_access_token_outs[last_index].pk
    assert result.context['before'] == expected_before
    assert result.context['next_url'] == expected_next_url


@pytest.mark.django_db
def test_inactive_account(inactive_account_client: Client):
    # When
    result = inactive_account_client.get(
        reverse('ui.accounts.apps.browse'),
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse(
            'ui.accounts.login',
            query=[
                ('next', reverse('ui.accounts.apps.browse')),
            ],
        ),
        fetch_redirect_response=False,
    )


@pytest.mark.django_db
def test_anonymous(client: Client):
    # When
    result = client.get(
        reverse('ui.accounts.apps.browse'),
    )

    # Then
    asserts.assertRedirects(
        result,
        reverse(
            'ui.accounts.login',
            query=[
                ('next', reverse('ui.accounts.apps.browse')),
            ],
        ),
        fetch_redirect_response=False,
    )
