"""
Themis middleware for timezone activation and theme context.
"""
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from django.utils import timezone


class TimezoneMiddleware:
    """
    Activate the user's effective timezone for each request.

    All datetime operations within the request will use the user's
    timezone. Falls back to UTC for anonymous users or on error.
    """

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

    def __call__(self, request):
        if request.user.is_authenticated and hasattr(request.user, "profile"):
            try:
                user_tz = ZoneInfo(request.user.profile.effective_timezone)
                timezone.activate(user_tz)
            except (ZoneInfoNotFoundError, Exception):
                timezone.activate(ZoneInfo("UTC"))
        else:
            timezone.activate(ZoneInfo("UTC"))

        response = self.get_response(request)
        timezone.deactivate()
        return response


class ThemeMiddleware:
    """
    Attach theme information to the request for use in templates.

    Sets request.themis_theme_mode, request.themis_theme_name, and
    request.themis_dark_theme_name for the context processor to read.
    """

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

    def __call__(self, request):
        if request.user.is_authenticated and hasattr(request.user, "profile"):
            profile = request.user.profile
            request.themis_theme_mode = profile.theme_mode
            request.themis_theme_name = profile.theme_name
            request.themis_dark_theme_name = profile.dark_theme_name
        else:
            request.themis_theme_mode = "auto"
            request.themis_theme_name = "corporate"
            request.themis_dark_theme_name = "business"

        return self.get_response(request)
