#!/usr/bin/python

import cgi, cgitb
import pgdb
import os, sys
import gpx

class pgdbImport (gpx.saxHandler):
    def __init__ (self, db, email):
	gpx.saxHandler.__init__(self)
	self.db	    = db.cursor()
	self.email  = email
	self.count  = 0

    def createTrackSegment (self):
	self.db.execute(
	    "INSERT INTO trackseg (owner, created) VALUES ('%s', NOW())"
	    % self.email )

    def createTrackPoint (self, trkpt):
	if not trkpt.has_key("time"): return
	self.count = self.count + 1
	self.db.execute( """
	    INSERT INTO trackpt (trackseg_id, stamp, point) 
		VALUES (CURRVAL('trackseg_id_seq'), '%(time)s', 
			'SRID=4326;POINT(%(lon)s %(lat)s %(ele)s)')
	    """ % trkpt )

def process_file (email, file):
    db = pgdb.connect( database = "limehouse" )
    handler = gpx.parse_file( file, pgdbImport, db, email )
    db.commit()
    return handler.count
    
def process_form ():
    q = cgi.FieldStorage()
    message = ""

    if q.has_key("gpx"):
	if not q.has_key("email"):
	    message = "You must supply an email address!"
	else:
	    email = q["email"].value
	    try:
		count = process_file( email, q["gpx"].file )
		message = "%d track points saved for %s." % (count, email)
	    except:
		db.rollback()
		message = "Couldn't parse your GPX file!"
		raise

    print """Content-type: text/html

<html>
<body>
<div>%s</div>
<form enctype="multipart/form-data" method="post">
<div>Email <input type="text" name="email" size="50" /></div>
<div>GPX Track <input type="file" name="gpx" /></div>
<div><input type="submit" value="Store" /></div>
</body>
</html>
	""" % message


if __name__ == "__main__":
    if os.environ.has_key("GATEWAY_INTERFACE"):
	cgitb.enable()
	process_form()
    else:
	process_file( sys.argv[1], sys.stdin )	
