import pytest

from django.urls import reverse

from aircox import models
from aircox.test import Interface
from aircox.views import base
from .conftest import FakeView


@pytest.fixture
def fake_request(station):
    return Interface(station=station)


@pytest.fixture
def base_view(fake_request):
    class View(base.BaseView, FakeView):
        model = models.Page
        request = fake_request

    return View()


@pytest.fixture
def base_api_view(fake_request):
    class View(base.BaseAPIView, FakeView):
        model = models.Program
        queryset = models.Program.objects.all()
        request = fake_request

    return View()


class TestBaseView:
    @pytest.mark.django_db
    def test_station(self, base_view, station):
        assert base_view.station == station

    @pytest.mark.django_db
    def test_get_sidebar_queryset(self, base_view, pages, published_pages):
        query = base_view.get_sidebar_queryset().values_list("id", flat=True)
        page_ids = {r.id for r in published_pages}
        assert set(query) == page_ids

    @pytest.mark.django_db
    def test_get_sidebar_url(self, base_view):
        assert base_view.get_sidebar_url() == reverse("page-list")

    @pytest.mark.django_db
    def test_get_context_data(self, base_view, station, published_pages):
        base_view.has_sidebar = True
        base_view.get_sidebar_queryset = lambda: published_pages
        context = base_view.get_context_data()
        assert context == {
            "view": base_view,
            "page": None,  # get_page() returns None
            "has_sidebar": base_view.has_sidebar,
            "has_filters": False,
            "sidebar_object_list": published_pages[: base_view.list_count],
            "sidebar_list_url": base_view.get_sidebar_url(),
            "model": base_view.model,
        }


class TestBaseAPIView:
    @pytest.mark.django_db
    def test_station(self, base_api_view, station):
        assert base_api_view.station == station

    @pytest.mark.django_db
    def test_get_queryset(self, base_api_view, station, programs):
        query = base_api_view.get_queryset()
        assert set(query.values_list("station", flat=True)) == {station.id}
