import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient

import urllib.parse
import json
import datetime
import time

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        query = self.get_argument('q')
        client = tornado.httpclient.HTTPClient()
        now = datetime.datetime.utcnow()
        request_count = 10
        for i in range(request_count):
            response = client.fetch("https://suggest.taobao.com/sug?code=utf-8&q=" + query)
            body = json.loads(response.body)
            #result_count = len(body['result'])
        after_date = datetime.datetime.utcnow()
        seconds_diff = time.mktime(after_date.timetuple()) - \
                time.mktime(now.timetuple())
        #print(result_count)
        tweets_per_second = request_count / seconds_diff
        self.write("""
<div style="text-align: center">
    <div style="font-size: 72px">%s</div>
    <div style="font-size: 144px">%.02f</div>
    <div style="font-size: 24px">request per second</div>
</div>""" % (query, tweets_per_second))

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
