# -*- 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

from hotpocket_common.constants import AssociationsSearchMode


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

    assert len(response.context['associations']) == 2
    assert response.context['associations'][0].pk == expected_association_ids[0]
    assert response.context['associations'][1].pk == expected_association_ids[1]
    assert response.context['params'].mode == AssociationsSearchMode.DEFAULT
    assert response.context['before'] is None
    assert response.context['next_url'] is None


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

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

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

    assert_default_mode_response_context(result, browsable_association_outs)


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

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

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

    assert_default_mode_response_context(result, browsable_association_outs)


@pytest.mark.django_db
def test_starred_mode(browsable_association_outs,
                      authenticated_client: Client,
                      starred_association_out,
                      ):
    # When
    result = authenticated_client.get(
        reverse('ui.associations.browse'),
        data={
            'mode': AssociationsSearchMode.STARRED.value,
        },
    )

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

    assert len(result.context['associations']) == 1
    assert result.context['associations'][0].pk == starred_association_out.pk
    assert result.context['params'].mode == AssociationsSearchMode.STARRED


@pytest.mark.django_db
def test_archived_mode(browsable_association_outs,
                       authenticated_client: Client,
                       archived_association_out,
                       ):
    # When
    result = authenticated_client.get(
        reverse('ui.associations.browse'),
        data={
            'mode': AssociationsSearchMode.ARCHIVED.value,
        },
    )

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

    assert len(result.context['associations']) == 1
    assert result.context['associations'][0].pk == archived_association_out.pk
    assert result.context['params'].mode == AssociationsSearchMode.ARCHIVED


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

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

    # When
    result = authenticated_client.get(
        reverse('ui.associations.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_association_outs[expected_before_index].pk
        expected_next_url = reverse(
            'ui.associations.browse',
            query=[
                ('before', expected_before),
                ('search', ''),
                ('limit', 12),
                ('mode', AssociationsSearchMode.DEFAULT.value),
            ],
        )

    assert len(result.context['associations']) == expected_length
    assert result.context['associations'][0].pk == paginatable_association_outs[first_index].pk
    assert result.context['associations'][-1].pk == paginatable_association_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.associations.browse'),
    )

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


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

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