import webapp2
import csv
import time

from google.appengine.api import logservice
from google.appengine.api import files

import config

class Level2Handler(webapp2.RequestHandler):
  def get(self):
    # Create a new Google Storage file
    filename = 'request.csv'
    gs_file = files.gs.create('/gs/%s/%s' % (config.gs_bucket_name, filename),
                               mime_type='text/csv')
    with files.open(gs_file, 'a') as f:
        # Create a csv writer that outputs to the Google Storage file
        w = csv.writer(f)
        for r in logservice.fetch(start_time=time.time()-5*60):
            w.writerow([r.start_time,r.method,r.resource,
                        r.status,r.latency,r.response_size,
                        r.user_agent if r.user_agent else "NULL"])
    # Finalize the file
    files.finalize(gs_file)

    # Render a HTML link to the file in the reponse body
    link_format = 'https://storage.cloud.google.com/{gs_bucket}/{filename}'
    link = link_format.format(gs_bucket=config.gs_bucket_name, filename=filename)
    self.response.write('<a href="{link}">{link}</a>'.format(link=link))

app = webapp2.WSGIApplication([('/solution/level2', Level2Handler)], debug=True)