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)
