# coding: utf-8

import re
from datetime import timedelta


DURATION_REGEXP = re.compile(
    r'\s*'.join(
        (
            r'^',
            r'(?:(?P<weeks>[0-9]+)w)?',
            r'(?:(?P<days>[0-9]+)d)?',
            r'(?:(?P<hours>[0-9]+)h)?',
            r'(?:(?P<minutes>[0-9]+)m)?',
            r'(?:(?P<seconds>[0-9]+)s)?',
            r'$',
        )
    )
)

UNITS = (
    (7 * 24 * 3600, 'w'),
    (24 * 3600, 'd'),
    (3600, 'h'),
    (60, 'm'),
    (1, 's'),
)


def parse_duration(duration):
    match = DURATION_REGEXP.match(duration)
    if not match:
        return None

    parts = match.groupdict(default=0)

    for unit in parts.keys():
        parts[unit] = int(parts[unit])

    try:
        return timedelta(**parts)

    except OverflowError:
        return None


def duration_string(td):

    remainder = td.total_seconds()
    result = []

    for lenght, unit in UNITS:
        num, remainder = divmod(remainder, lenght)
        if num:
            result.append('%d%s' % (num, unit))

    return ' '.join(result)
