# Copyright (C) 2018-2025 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later

from django.utils.translation import gettext_lazy as _

seconds = (_('second'), _('seconds'))
minutes = (_('minute'), _('minutes'))
hours = (_('hour'), _('hours'))
days = (_('day'), _('days'))
weeks = (_('week'), _('weeks'))


def plural(x):
    if x == 1:
        return 0
    return 1


def pretty_duration(duration):
    """
    I receive datetime.timedelta object
    You receive string object
    """
    text = []
    sec = duration.seconds
    d = duration.days

    if d >= 7:
        w = d // 7
        text.append(str(w) + ' ' + weeks[plural(w)])
        d -= w * 7
    if d > 0:
        text.append(str(d) + ' ' + days[plural(d)])

    if sec >= 3600:
        h = sec // 3600
        text.append(str(h) + ' ' + hours[plural(h)])
        sec -= h * 3600

    if sec >= 60:
        m = sec // 60
        text.append(str(m) + ' ' + minutes[plural(m)])
        sec -= m * 60

    if sec > 0:
        text.append(str(sec) + ' ' + seconds[plural(sec)])

    if len(text) == 0:
        return ''
    if len(text) == 1:
        return text[0]
    if len(text) >= 2:
        return ', '.join(t for t in text[:-1]) + ' ' + _('and') + ' ' + text[-1]
