"""
Template tags and filters for Themis.
Provides formatting filters based on user preferences.
"""
from django import template
from django.utils.safestring import mark_safe

from themis.utils import format_date_for_user, format_number_for_user, format_time_for_user

register = template.Library()


@register.filter
def user_date(date_value, user):
    """
    Format a date according to user's preferred format.

    Usage: {{ event.date|user_date:request.user }}
    """
    if not date_value:
        return ""
    return format_date_for_user(date_value, user)


@register.filter
def user_time(time_value, user):
    """
    Format a time according to user's 12/24-hour preference.

    Usage: {{ event.time|user_time:request.user }}
    """
    if not time_value:
        return ""
    return format_time_for_user(time_value, user)


@register.filter
def user_number(number_value, user):
    """
    Format a number with user's preferred thousand separator.

    Usage: {{ organization.revenue|user_number:request.user }}
    """
    if number_value is None:
        return ""
    return format_number_for_user(number_value, user)


@register.simple_tag
def user_timezone_name(user):
    """
    Display user's effective timezone name.

    Usage: {% user_timezone_name request.user %}
    """
    if hasattr(user, "profile"):
        return user.profile.effective_timezone
    return "UTC"


@register.simple_tag(takes_context=True)
def themis_body_attrs(context):
    """
    Generate body tag data attributes for datetime widgets.

    Provides user date/time format and week-start preferences as data
    attributes so JavaScript pickers can respect user settings.

    Usage: <body {% themis_body_attrs %}>

    Emits:
        data-user-date-format  — e.g. "YYYY-MM-DD", "DD/MM/YYYY"
        data-user-time-format  — "24-hour" or "12-hour"
        data-user-week-start   — "monday", "sunday", or "saturday"
    """
    request = context.get("request")
    if not request or not request.user.is_authenticated:
        return mark_safe(
            'data-user-date-format="YYYY-MM-DD" '
            'data-user-time-format="24-hour" '
            'data-user-week-start="monday"'
        )

    user = request.user
    date_format = "YYYY-MM-DD"
    time_format = "24-hour"
    week_start = "monday"

    if hasattr(user, "profile"):
        date_format = user.profile.date_format
        time_format = user.profile.time_format
        week_start = user.profile.week_start

    return mark_safe(
        f'data-user-date-format="{date_format}" '
        f'data-user-time-format="{time_format}" '
        f'data-user-week-start="{week_start}"'
    )
