# > !Currency.py.Rates/py

import pickle
import re
import string
import urllib


_re_date = re.compile(r"EFFECTIVE *(\d\d-\w\w\w-\d\d)")
_re_rate = re.compile(r"([A-Z]{3,3}) ([^0-9]+?) +([0-9.]+)? +([0-9.]+)( +)?([^0-9]*)$")


def load(cache):
    global _date, _rates
    c = open(cache, 'r')
    _date = pickle.load(c)
    _rates = pickle.load(c)
    c.close()


def update(url, cache, us, dollar):
    global _date, _rates
    rates = [(us, dollar, 1.0)]
    u = urllib.urlopen(url)
    c = open(cache, 'w')
    while 1:
        l = u.readline()
        m = _re_date.match(l)
        if m:
            break
    _date = m.group(1)
    while 1:
        l = u.readline()
        if l[:4] == 'CODE':
            break
    l = u.readline()
    while 1:
        l = u.readline()
        m = _re_rate.match(l[:-2])
        if m is None:
            break
        rates.append((string.capwords(string.lower(m.group(2))),
                      string.capwords(string.lower(m.group(6))),
                      eval(m.group(4))))
    u.close()
    pickle.dump(_date, c, 1)
    _rates = rates
    pickle.dump(_rates, c, 1)
    c.close()


def currencies(format):
    return map(lambda rate, format = format:
               format % {'country': rate[0], 'currency': rate[1], 'rate': rate[2]},
               _rates)


def currency(format, i):
    return format % {'country': _rates[i][0], 'currency': _rates[i][1], 'rate': _rates[i][2]}


def date():
    return _date


def convert(currency, value):
    conversion = []
    base = float(value) / _rates[currency][2]
    for rate in _rates:
        conversion.append(base * rate[2])
    return conversion
