import wsgiref.handlers
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db

class Location(db.Model):
  lat = db.IntegerProperty()
  lon = db.IntegerProperty()
  date = db.DateTimeProperty(auto_now_add=True)


class LocationService(webapp.RequestHandler):

  def printloc(self,location):
      return '<location lat=\'%(lat)s\' lon=\'%(lon)s\'></location>\n' % {'lat':location.lat, 'lon':location.lon} 
        
  def get(self):
    locations = db.GqlQuery("SELECT * FROM Location ORDER BY date DESC LIMIT 10")
    self.response.headers['Content-Type'] = 'text/xml'
    self.response.out.write('<list>')
    for l in locations:
        self.response.out.write(self.printloc(l))    
    self.response.out.write('</list>')
           
  def post(self):
      location = Location()
      location.lat = int(self.request.get('lat'))
      location.lon = int(self.request.get('lon'))
      location.put()
      self.response.out.write(self.printloc(location))
         
def main():
  application = webapp.WSGIApplication(
                                       [('/endpoint', LocationService)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()