#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from xml.sax import make_parser
from xml.sax.handler import ContentHandler

class NodeFinder(ContentHandler):
    def __init__(self, results):
        self.results = results

    def startElement(self, name, attrs):
        if name == "node":
            id = attrs.getValue("id")
            for result in self.results:
                if result['type'] == 'area':
                    for nd in range(0, len(result['nodes'])):
                        if id == result['nodes'][nd]:
                            # It's tempting to break, but a way may have a node
                            # more than once.
                            result['nodes'][nd] = (id,
                                    {
                                    'lat':attrs.getValue("lat"),
                                    'lon':attrs.getValue("lon"),
                                    })


class OpeningHoursHandler(ContentHandler):
    def __init__(self):
        self.curtags = {}
        self.type = ""
        self.parentattrs = None
        self.curnodes = []
        self.results = []

    def startElement(self, name, attrs):
        if name == "node" or name == "way":
            self.type = name
            self.parentattrs = attrs
            self.curtags = {}
            self.curnodes = []
        elif name == "tag":
            self.curtags[attrs.getValue("k")] = attrs.getValue("v")
        elif name == "nd":
            self.curnodes.append(attrs.getValue("ref"))

    def endElement(self, name):
        if "opening_hours" in self.curtags and name in ("node", "way"):
            if name == "node":
                res = {
                        'type':'node',
                        'node': {
                            'lat':self.parentattrs.getValue("lat"),
                            'lon':self.parentattrs.getValue("lon"),
                            }
                        }
            elif name == "way":
                type = 'way'
                if self.curnodes[0] == self.curnodes[-1]:
                    type = 'area'
                else:
                    # Ignore non-closed ways
                    type = 'way'
                    return False
                res = {
                        'type':type,
                        'nodes': self.curnodes
                        }

            res['tags'] = self.curtags
            res['id'] = self.parentattrs.getValue("id")
            self.results.append(res)

if __name__ == "__main__":
    import codecs
    sys.stdout = codecs.getwriter("utf8")(sys.stdout) # Always print UTF-8
    sys.stderr = codecs.getwriter("utf8")(sys.stderr) # Always print UTF-8

    # Find nodes and ways with opening_hours set
    oh = OpeningHoursHandler()
    saxparser = make_parser()
    saxparser.setContentHandler(oh)
    saxparser.parse(sys.argv[1])

    # Resolve node refs for areas
    nf = NodeFinder(oh.results)
    saxparser2 = make_parser()
    saxparser2.setContentHandler(nf)
    saxparser2.parse(sys.argv[1])

    # Output results
    for place in nf.results:
        for tag in place['tags']:
            print("tag:%s=%s=%s" % (place['id'], tag, place['tags'][tag]))
        if place['type'] == "node":
            print("node:%s=%s,%s" % (place['id'], place['node']['lat'], place['node']['lon']))
        elif place['type'] == "area":
            for node in place['nodes']:
                print "node:%s@%s=%s,%s" % (node[0], place['id'], node[1]['lat'], node[1]['lon'])
            #    poly = ">".join([(",".join((a['lat'], a['lon']))) for a in place['nodes']])
            #print("area:%s=%s" % (place['id'], poly))
        print ""
