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(
    scope='https://www.googleapis.com/auth/bigquery')
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 = files.gs.create('/gs/%s' % gs_path, mime_type='text/csv')
    with files.open(filename, 'a') as f:
        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"])
    files.finalize(filename)
    # 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 config.py
    # TODO3: missing arg: projectId, datasetId, tableId from config.py
    result = service.jobs().insert(projectId=config.project_id,
                         body={'projectId': config.project_id,
                               'configuration':{
                                 'load':{
                                   'sourceUris': ['gs://%s' % TODO1],
                                   'schema': {
                                     'fields': TODO2,
                                   },
                                   'destinationTable': {
                                     'projectId': TODO3,
                                     'datasetId': TODO3,
                                     'tableId': TODO3,
                                   },
                                   'createDisposition':'CREATE_IF_NEEDED',
                                   'writeDisposition':'WRITE_TRUNCATE',
                                   'encoding':'UTF-8'
                              }}}).execute()
    # 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 = service.jobs()
    # Get the job status
    # TODO: missing arg: jobId
    status = jobs.get(projectId=config.project_id,
                      jobId=TODO).execute()
    # Write the job status to the reponse body
    self.response.write(status)


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