"""
Some simple macros that are used to e.g. sort things within the jinja
templates. For the relevant documentation please see:

http://jinja.pocoo.org/docs/2.9/api/#custom-filters

Created 26-09-2017 by Josh Borrow (joshua.borrow@durham.ac.uk)
"""

import datetime
import dateutil.parser as dp
from random import randint as rand

def sort_cards(cards):
    """
    Sort the cards by date. 'cards' should have the following structure:
    [
       {
         ...
         date: "date"
       },
    ]
    
    A list will be returned where the cards are sorted by date.
    """

    # We add a random number of seconds in case we have a number of
    # cards on the same date.

    dates = [
        dp.parse(card["date"]) + datetime.timedelta(seconds=rand(0, 10000))
        for card in cards
    ]

    _, cards = zip(*sorted(zip(dates, cards)))

    # We want the newest to appear first.
    return reversed(cards)