from django import template

register = template.Library()


@register.filter
def natural_duration(value):
    if not value:
        return
    value = int(value)
    days = int(value / 86400)
    remainder = value % 86400
    hours = int(remainder / 3600)
    minutes = int((remainder % 3600) / 60)
    seconds = remainder % 60
    parts = []
    if days:
        parts.append(f"{days} day{'s' if days != 1 else ''}")
    if hours:
        parts.append(f"{hours} hour{'s' if hours != 1 else ''}")
    if minutes:
        parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")
    if seconds or not parts:
        parts.append(f"{seconds} second{'s' if seconds != 1 else ''}")
    if len(parts) == 1:
        return parts[0]
    return ", ".join(parts[:-1]) + " and " + parts[-1]
