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
    # TODO: missing arg: '/gs/bucket_name/filename.csv'
    gs_file = files.gs.create(TODO, mime_type='text/csv')
    # TODO: missing arg: gs_file
    with files.open(TODO, '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
    # TODO: missing arg: gs_file
    files.finalize(TODO)
    
    # Render a HTML link to the file in the reponse body
    link_format = 'https://storage.cloud.google.com/{gs_bucket}/{filename}'
    # TODO1: missing arg: gs_bucket
    # TODO2: missing arg: filename
    link = link_format.format(gs_bucket=TODO1, filename=TODO2)
    self.response.write('<a href="{link}">{link}</a>'.format(link=link))

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