import webapp2
import csv
import time
import httplib2

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

from apiclient.discovery import build
from oauth2client.appengine import AppAssertionCredentials

import config

# Authenticate w/ bigquery scope
credentials = AppAssertionCredentials(
http = credentials.authorize(http=httplib2.Http())
# Build bigquery service instance
service = build('bigquery','v2',http=http)

class Level3Handler(webapp2.RequestHandler):
  def get(self):
    self.response.headers['content-type'] = 'text/plain'
    gs_path = '%s/requests.csv' % config.gs_bucket_name
    filename ='/gs/%s' % gs_path, mime_type='text/csv')
    with, 'a') as f:
        w = csv.writer(f)
        for r in logservice.fetch(start_time=time.time()-5*60):
                        r.user_agent if r.user_agent else "NULL"])
    # Insert a new `load` job for the Google Storage File
    # TODO1: missing arg: sourcesUris that point to your google storage file
    # TODO2: missing arg: big query table schema from
    # TODO3: missing arg: projectId, datasetId, tableId from
    result =,
                         body={'projectId': config.project_id,
                                   'sourceUris': ['gs://%s' % TODO1],
                                   'schema': {
                                     'fields': TODO2,
                                   'destinationTable': {
                                     'projectId': TODO3,
                                     'datasetId': TODO3,
                                     'tableId': TODO3,
    # Redirect the client to the CheckHandler
    # TODO: missing arg: bigquery job id
    self.redirect('/level3/check/%s' % result['TODO']['TODO'])

class CheckHandler(webapp2.RequestHandler):
  def get(self, job):
    jobs =
    # Get the job status
    # TODO: missing arg: jobId
    status = jobs.get(projectId=config.project_id,
    # Write the job status to the reponse body

app = webapp2.WSGIApplication([('/level3', Level3Handler),
                               ('/level3/check/(.*)', CheckHandler)],