import re
from datetime import datetime

from django import template

register = template.Library()


@register.filter(name="add_class")
def add_class(field, css_class):
    if field.field.widget.__class__.__name__ == "CheckboxInput":
        return field.as_widget()
    return field.as_widget(attrs={"class": css_class})


@register.simple_tag
def current_date(format):
    return datetime.now().strftime(format)


@register.filter
def note_position(note, article_length):
    if not article_length or article_length == 0:
        return ""
    match = re.search(r"start:(\d+)", note)
    if match:
        start = int(match.group(1))
        percentage = (start / article_length) * 100
        return f"style='top: {percentage}%'"
    return ""


@register.filter
def note_text(note):
    return re.sub(r"\s*\[start:\d+\|end:\d+\]$", "", note)


@register.filter
def get_item(dictionary, key):
    if isinstance(dictionary, dict):
        return dictionary.get(key)
    try:
        return dictionary[int(key)]
    except (TypeError, ValueError, KeyError):
        return None


@register.filter
def agent_session_html(logdata, scrobble_id=None):
    return logdata.as_html(scrobble_id=scrobble_id)


@register.filter
def workout_html(logdata, units="metric"):
    return logdata.as_html(units=units)
