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

import urllib2
import cgi

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from django.utils import simplejson
from operator import itemgetter

class RouteInfo(db.Model):
	routeName = db.StringProperty()
	isReturn = db.IntegerProperty()
	stopName = db.StringProperty()
	nextStopName = db.StringProperty()

class MainHandler(webapp.RequestHandler):
	def get(self):
		self.response.headers.add_header("Cache-Control", "no-cache")
		stopName = self.request.get('stopName')
		req = urllib2.Request('http://www.taipeibus.taipei.gov.tw/Asp/GetTimeByRouteStop4.aspx?GSName=%s' % stopName.encode('utf-8'))
		response = urllib2.urlopen(req)
		content = response.read().split("|")
		busLines=[]

		for line in content:
			try:
				(routeName, lon, lat, isReturn, iDontKnowWhatItIs, estTime) = line.split(",")
			except ValueError:
				continue

			routeName=routeName.strip(" _").decode('utf-8')
			isReturn=int(isReturn.strip(" _"))
			estTime=int(estTime.strip(" _"))

			try: 
				nextStopName = RouteInfo.gql( "WHERE routeName = :1 "
							"AND isReturn = :2 "
							"AND stopName = :3 "
							"LIMIT 1",
							routeName,
							isReturn,
							stopName)[0].nextStopName
			except ValueError:
				nextStopName = ""
				

			# mark those which < 0 as unknown
			if estTime<0:
				estTime=86400

			busLines.append({'routeName': routeName, 'nextStopName': nextStopName, 'estTime': estTime})

		# sort the lines
		busLines = sorted(busLines,key=itemgetter('estTime'))

		# encapsulize
		data = {'requestName': stopName, 'content': busLines}

		# send data
		self.response.out.write(simplejson.dumps(data))




def main():
	application = webapp.WSGIApplication([('/getstopbus', MainHandler)])
	util.run_wsgi_app(application)


if __name__ == '__main__':
	main()

@@ -1285,37 +1285,37 @@
 pName%0A%09%09%09except 
-Value
+Index
 Error:%0A%09%09%09%09nextS
@@ -1325,16 +1325,23 @@
 Name = %22
+unknown
 %22%0A%09%09%09%09%0A%0A

fix IndexError