#!/usr/bin/env python

""" A REST client to retrieve information from the BIXI bicycle system. """

__PROGRAM__ = "get-bixi"
__VERSION__ = "0.0"
__AUTHOR__ = "Stephane Bortzmeyer <stephane@bortzmeyer.org>"

import sys 
import urllib
import lxml
from lxml import etree

url = "https://profil.bixi.ca/data/bikeStations.xml"

class AppURLopener(urllib.FancyURLopener):
    version = "%s/%s (Bortzmeyer's get-bixi.py; Python %s; http://www.bortzmeyer.org/velib-rest.html)" % (__PROGRAM__, __VERSION__, sys.version[0:5])
    
def usage():
    print >>sys.stderr, ("Usage: %s station-name" % sys.argv[0])

dump_all = False
    
if len(sys.argv) == 1:
    usage()
    dump_all = True
elif len(sys.argv) == 2:
    # If you are not in UTF-8...
    #station_name = unicode(sys.argv[1].strip(), "latin-1")
    station_name = unicode(sys.argv[1].strip())
else:
    usage()
    sys.exit(1)
    
urllib._urlopener = AppURLopener()
data = urllib.urlopen(url).read()
root = etree.fromstring(data)
if dump_all:
    print "List of all the stations:"
    for name in root.xpath("station/name"):
        # If you are not in UTF-8...
        #print name.text.encode("Latin-1", 'replace')
        print name.text
else:
    # No conditional Xpath expressions in etree?
    for station in root.xpath("station"):
        raw_name = station.xpath("name/text()")[0]
        this_station = unicode(raw_name).strip()
        if this_station == station_name:
            if str(station.xpath("installed/text()")[0]).strip() == "true":
                installed = True
            else:
                installed = False
            bikes = int(station.xpath("nbBikes/text()")[0])
            slots = int(station.xpath("nbEmptyDocks/text()")[0])
            if installed:
                print "%s: %i bikes, %i empty docks" % (this_station, bikes, slots)
            else:
                print "%s: not yet installed" % this_station
            break



