#!/usr/bin/python

from xml.dom import minidom
import sys
import urllib
import codecs

API_URL = "http://api.openstreetmap.org/api/0.6"

def get_osm_version(elementName, id):
    # this is inefficient because it makes an API call for every element
    urlstr = API_URL + "/" + elementName + "/" + id
    url = urllib.urlopen(urlstr)
    xmlString = url.read()
    parsed = minidom.parseString(xmlString)
    element = parsed.getElementsByTagName(elementName)[0]
    return element.attributes["version"].value

def fivetosix(filename):
    osmFile = minidom.parse(filename)
    osmElement = osmFile.firstChild;
    versionAttribute = osmElement.attributes["version"]
    versionValue = versionAttribute.value
    if versionValue != u"0.5":
        raise Exception, "Only OSM files of version 0.5 supported! " + \
            "Yours is " + versionValue + "."

    versionAttribute.value = u"0.6"

    # get all nodes, ways and relations from file
    elements = osmFile.getElementsByTagName("node")
    elements.extend(osmFile.getElementsByTagName("way"))
    elements.extend(osmFile.getElementsByTagName("relation"))

    # for all elements with non-negative id get version number from API
    count = 0
    for element in elements:
        type = element.nodeName
        id = element.attributes["id"].value

        count += 1
        print "Element", count, "of", elements.length, "(" + type, id + ")"

        if int(id) < 0 or element.hasAttribute("version"):
            continue

        version = get_osm_version(type, id)
        element.attributes["version"] = version

    outfilename = filename.replace(".osm", "-6.osm")
    print "Writing to", outfilename + "..."

    enc = "UTF-8"
    outfile = codecs.open(outfilename, "w", enc)
    osmFile.writexml(outfile, encoding=enc)

def main():
    for filename in sys.argv[1:]:
        fivetosix(filename)

if __name__ == "__main__":
    sys.exit(main())
