from zoneinfo import ZoneInfo

from django.db.models import Q
from django.utils import timezone as tz

from .models import Station
from .utils import Redirect

__all__ = ("AircoxMiddleware",)


class AircoxMiddleware(object):
    """Middleware used to get default info for the given website.

    It provide following request attributes:
    - ``station``: current Station

    This middleware must be set after the middleware
        'django.contrib.auth.middleware.AuthenticationMiddleware',
    """

    timezone_session_key = "aircox.timezone"

    def __init__(self, get_response):
        self.get_response = get_response

    def get_station(self, request):
        """Return station for the provided request."""
        host = request.get_host()
        expr = Q(default=True) | Q(hosts=host) | Q(hosts__contains=host + "\n")
        return Station.objects.filter(expr).order_by("default").first()

    def init_timezone(self, request):
        # note: later we can use http://freegeoip.net/ on user side if
        # required
        timezone = None
        try:
            timezone = request.session.get(self.timezone_session_key)
            if timezone:
                timezone = ZoneInfo(timezone)
                tz.activate(timezone)
        except Exception:
            pass

    def __call__(self, request):
        self.init_timezone(request)
        request.station = self.get_station(request)
        try:
            return self.get_response(request)
        except Redirect:
            return
