require 'rubygems'
require 'simplegeo'
SimpleGeo::Client.set_credentials('DWwk7QhYxPJQWC5HR8JWaDqT7vnzuH8F', 'VUbSRnez5EbPWyRXbswNXkWFTsnSHYmt')

# lat, long
places = SimpleGeo::Client.get_places(44.8378,-0.5761)

#puts places.inspect


id=0

puts "<?xml version='1.0' encoding='UTF-8'?>
<osm version='0.6' generator='JOSM'>"

places[:features].each{ |feature|
    lat = feature[:geometry][:coordinates][1]
    lon = feature[:geometry][:coordinates][0]
    ref = feature[:id]
    tag = {'ref:simplegeo'=>ref}
    feature[:properties].each{ |k,v|
        tag[k.to_s] = v.to_s.gsub("'", "&#39;").gsub("&", "&amp;")
    }
    if feature[:properties][:classifiers] and feature[:properties][:classifiers].size > 0 then
        # FIXME il peut y en avoir plusiers
        feature[:properties][:classifiers][0].each{ |k,v|
            tag["classifiers:#{k.to_s}"] = v.to_s.gsub("'", "&#39;").gsub("&", "&amp;")
        }
    end
    tag.delete('classifiers')
    tag.delete('distance')
    tag['source'] = tag['owner']
    tag.delete('owner')
    # TODO assert tag['owner'] == 'simplegeo'

    puts "  <node id='#{id-=1}' timestamp='2009-01-24T13:40:28Z' version='0' lat='#{lat}' lon='#{lon}'>"
    tag.each{ |k,v|
        puts "<tag k='#{k}' v='#{v}'/>"
    }
    puts "  </node>"
}

puts "</osm>"
