#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import, print_function)

from itertools import groupby

from calibre_plugins.overdrive_link.recipe_81611_1 import int_to_roman
from calibre_plugins.overdrive_link.recipe_413172_1 import spoken_number


__license__ = 'GPL v3'
__copyright__ = '2012-2025, John Howell <jhowell@acm.org>'


def word_number(i):
    return spoken_number(i).replace('-', ' ')


NUMERIC_RANKS = {'one': 'first', 'two': 'second', 'three': 'third', 'five': 'fifth',
                 'eight': 'eighth', 'nine': 'ninth', 'twelve': 'twelfth'}


def word_rank(i):
    words = word_number(i).split()
    w = words.pop(-1)

    if w in NUMERIC_RANKS:
        w = NUMERIC_RANKS[w]
    elif w[-1] == 'y':
        w = w[0:-1] + 'ieth'
    else:
        w = w + 'th'

    words.append(w)
    return ' '.join(words)


def word_year(i):
    if i % 100 < 10:
        return word_number(i)

    return word_number(i // 100) + ' ' + word_number(i % 100)   # century then year


def numeric_rank(i):
    return "%d%s" % (i, word_rank(i)[-2:])


def roman_number(i):
    return int_to_roman(i).lower()


def value_unit(value, unit):
    if value == 1:
        return '1 %s' % unit            # singular: 1 book

    if unit[-1] == 's':
        units = '%ses' % unit           # plural: 2 bosses

    elif unit[-1] == 'y' and unit != 'day':
        units = '%sies' % unit[:-1]     # plural: 3 libraries

    else:
        units = '%ss' % unit            # plural: 4 books

    return '%s %s' % ('{:,}'.format(value), units)  # add commas for large numbers


def range_str(data):
    # convert a list of numbers to a string showing ranges
    str_list = []
    for key, group in groupby(enumerate(sorted(data)), lambda i, x: i - x):
        # groupby breaks into groups having the same key
        # in this case successive values will have the same key
        group = list(group)
        if len(group) > 1:
            str_list.append('%d-%d' % (group[0][1], group[-1][1]))
        else:
            str_list.append('%d' % group[0][1])

    return ', '.join(str_list)


def main():
    for i in range(1, 102):
        print("%d : '%s', '%s', '%s', '%s'," % (i, word_number(i), word_rank(i), numeric_rank(i), roman_number(i)))

    for i in range(1990, 2020):
        print("%d : '%s'" % (i, word_year(i)))


if __name__ == '__main__':
    main()
