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
    result = service.jobs().insert(projectId=config.project_id,
                         body={'projectId': config.project_id,
                               'configuration':{
                                 'load':{
                                   'sourceUris': ['gs://%s' % gs_path],
                                   'schema': {
                                     'fields': config.bigquery_schema
                                   },
                                   'destinationTable': {
                                     'projectId': config.project_id,
                                     'datasetId': config.bigquery_dataset_id,
                                     'tableId': config.bigquery_table_id
                                   },
                                   'createDisposition':'CREATE_IF_NEEDED',
                                   'writeDisposition':'WRITE_TRUNCATE',
                                   'encoding':'UTF-8'
                              }}}).execute()
    # Redirect the client to the CheckHandler
    self.redirect('/solution/level3/check/%s' % result['jobReference']['jobId'])

class CheckHandler(webapp2.RequestHandler):
  def get(self, job):
    jobs = service.jobs()
    # Get the job status
    status = jobs.get(projectId=config.project_id,
                      jobId=job).execute()
    # Write the job status to the reponse body
    self.response.write(status)


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