#! /usr/bin/env python

import ecbxrate
import argparse
import datetime

try:
    import cdecimal as decimal
except ImportError:
    import decimal

parser = argparse.ArgumentParser(description='Fetch exchange rates from the European Central Bank')
parser.add_argument('-d', '--db', '--database',
                    dest='db_url', action='store',
                    nargs='?',
                    help='the database URL')
parser.add_argument('args', nargs='+',
                    help="""may be 'initialise', 'update', 'status'
                    or alternatively a sequence of
                     YYYY-MM-DD from-currency to-currency""")

args = parser.parse_args()

store = ecbxrate.ExchangeRateStore(args.db_url)

arg = args.args[0]
if arg == 'initialise':
    rates, dates = store.initialise()
    print 'Initialised with %u rates covering %u days' % (rates, dates)
    exit(0)
elif arg == 'update':
    rates, date = store.update()
    print 'Updated %u rates for %s' % (rates, date)
    exit(0)
elif arg == 'status':
    last_update = store.last_updated()
    print 'Last updated for %s' % last_update
    exit(0)
    
if len(args.args) > 2:
    if arg == 'today' or arg == 'latest' or arg == 'yesterday':
        the_date = arg
    else:
        the_date = datetime.datetime.strptime(arg, '%Y-%m-%d').date()
        
    from_currency = args.args[1].upper()
    to_currency = args.args[2].upper()

    date, rate = store.get_rate(from_currency, to_currency, the_date,
                                closest_rate=True)

    if rate is None:
        print 'No known rate for %s:%s on %s' % (from_currency, to_currency,
                                                 the_date)
        exit(1)
        
    print 'At %s, %s:%s = %s' % (date, from_currency, to_currency, rate)

    if len(args.args) > 3:
        amount = decimal.Decimal(args.args[3])

        q = decimal.Decimal('.01')
        
        converted = (amount * rate).quantize(q,
                                             rounding=decimal.ROUND_HALF_EVEN)
        print '%s %s = %s %s' % (from_currency, amount,
                                 to_currency, converted)
