import pytest
from django.utils import timezone as tz

from django.conf import settings
from aircox.middleware import AircoxMiddleware

from .conftest import req_factory


settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ["unknown-host"]


@pytest.fixture
def middleware():
    return AircoxMiddleware(lambda r: r)


class TestAircoxMiddleware:
    @pytest.mark.django_db
    def test_get_station(self, middleware, station, sub_station):
        req = req_factory.get("/tmp/test", headers={"host": sub_station.hosts})
        assert middleware.get_station(req) == sub_station

        req = req_factory.get("/tmp/test", headers={"host": station.hosts})
        assert middleware.get_station(req) == station

    @pytest.mark.django_db
    def test_get_station_use_default(self, middleware, station, stations):
        req = req_factory.get("/tmp/test", headers={"host": "unknown-host"})
        assert middleware.get_station(req) == station

    @pytest.mark.django_db
    def test_init_timezone(self, middleware):
        req = req_factory.get("/tmp/test")
        req.session = {middleware.timezone_session_key: "Europe/Brussels"}
        middleware.init_timezone(req)

        current_tz = tz.get_current_timezone()
        assert current_tz.key == "Europe/Brussels"

    @pytest.mark.django_db
    def test_init_timezone_wrong_timezone(self, middleware):
        req = req_factory.get("/tmp/test")
        req.session = {middleware.timezone_session_key: "Oceania/Arlon"}
        middleware.init_timezone(req)

        current_tz = tz.get_current_timezone()
        assert current_tz.key != "Oceania/Arlon"
