#!/usr/bin/env python
"""osm-convert.py -- retag Lithuanian roads by their ref tag.

The roads are tagged as follows:

  Magistraliniai (refs like A1, A15) -- trunk
  Krašto (refs like 102, 207) -- primary
  Rajoniniai (refs like 1007, 5218) -- secondary

"""
from lxml.etree import parse, tostring
from bz2 import BZ2File
import re
from StringIO import StringIO
from httplib import HTTPConnection


rajoninis = re.compile("[0-9]{4}")
krasto = re.compile("[0-9]{3}")
magistralinis = re.compile("[Aa][0-9]+")

changeset_body = """\
<osm>
  <changeset>
    <tag k="created_by" v="osm-convert.py"/>
    <tag k="comment" v="Promoting magistraliniai to trunk, krasto to primary, rajoniniai to secondary by an automated script."/>
  </changeset>
</osm>
"""

print len(changeset_body)

def main():
    #dump = parse(BZ2File("lithuania.osm.2010-02-14.bz2"))
    dump = parse(BZ2File("map.osm.bz2"))

    st, msg, changeset = http("PUT", "/api/0.6/changeset/create",
                              changeset_body)
    if st != 200:
        print st, msg
        print changeset
        return
    print "Opened changeset %s." % changeset

    count = 0
    for way in dump.xpath("//way[tag/@k='highway']"):
        ref = "".join(way.xpath("tag[@k='ref']/@v"))
        if (ref and
            (rajoninis.match(ref) or krasto.match(ref)
             or magistralinis.match(ref))):
            print "%s..." % ref
            way_id = way.get("id")
            st, exp, body = http("GET", "/api/0.6/way/" + way_id)
            if str(st) != "200":
                print "No way", way.get("id")
                continue
            copy = parse(StringIO(body))
            highway = copy.xpath("//tag[@k='highway']")[0]
            way = copy.find("way")
            way.set("changeset", changeset)
            if rajoninis.match(ref):
                highway.set("v", "secondary")
            elif krasto.match(ref):
                highway.set("v", "primary")
            elif magistralinis.match(ref):
                highway.set("v", "trunk")
            st, err, body = http("PUT", '/api/0.6/way/' + way_id,
                                 tostring(copy))
            if st == 200:
                count += 1
            else:
                print st, err
                print body
    print http("PUT", "/api/0.6/changeset/%s/close" % changeset)
    print "%s ways updated." % count


auth = "alga:iPh2eesh"
server = 'api06.dev.openstreetmap.org'

def http(method, path, body=""):
    conn = HTTPConnection(server)
    headers = {
        'User-Agent': 'LTUpgradeScript',
        'Content-Type': 'text/xml; charset=UTF-8',
        'Authorization': 'Basic %s' % auth.encode('base64').strip(),
        }
    conn.request(method, path, body, headers)
    response = conn.getresponse()
    return response.status, response.reason, response.read()


if __name__ == '__main__':
    main()
