#!/usr/bin/python

"""
Fetch currency conversions from xe.com.

WARNING: Do not use this module for any commercial purposes, unless you have
obtain an explicit license to use the service provided by XE.com. For further
details please read the Terms and Conditions available at http://www.xe.com.

In fact, their site suggests that this module shouldn't be used at all.  So 
if you choose to, you do so at your own risk.  The author takes no 
responsibility for use of this code.

Example:

    >>> xecurrency.convert(10.0, 'USD', 'GBP')
    6.12961

"""
from __future__ import unicode_literals

__author__  = 'Michael Stella <xecurrency@thismetalsky.org>'
__license__ = 'Apache 2.0'
__version__ = '0.1'

import re, sys
import mechanize
try:
    from ClientForm import ItemNotFoundError
except:
    from mechanize import ItemNotFoundError

def convert(value, source, target):
    """Converts currency.

    arguments:
        value:  float
        source:
        target: three-character currency codes

    returns:
        value in target currency, as a float

    raises:
        InvalidCurrencyError
        ValueError (if value is not float)
        urllib2 errors

    """
    # make sure we have a float
    if type(value) is not float:
        raise ValueError("Value must be a float")

    # here's our "browser"
    br = mechanize.Browser()
    br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

    # get the first page
    rsp = br.open('http://www.xe.com/ucc')

    # fill out form
    br.select_form(nr=1)
    try:
        br.form.set_value([target.upper()], name='To', nr=1)
        br.form.set_value([source.upper()], name='From', nr=1)
    except ItemNotFoundError, e:
        m = re.match("insufficient items with name '(.+?)'", str(e))
        raise InvalidCurrencyError("Invalid currency '{0}'".format(m.group(1)))

    br.form.set_value(unicode(value), name='Amount', nr=0)

    rsp = br.submit()

    m = re.search('<td width="46%" align="[^"]+">([0-9.]+).nbsp;{0}<!-- WARNING'.format(target.upper()), rsp.read())
    if m:
        return float(m.group(1))



class InvalidCurrencyError(ValueError):
    pass


if __name__ == '__main__':
    print convert(float(sys.argv[1]), *sys.argv[2:4])

"""
Copyright 2011 Michael Stella

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""


