import argparse

import json
import requests
import time
import csv
import pprint
import datetime
import sys
import httplib2
import random

from apiclient.errors import HttpError
from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from time import sleep

#articles = "https://dataclips.heroku.com/wzskvliqdvaythtknaesjdtctlyn-articles-by-pub-date.json"
#user_agent = {'User-agent': 'Mozilla/5.0'}

"""First command line arg is the file,
the second is the days-forward period
the third is places vs articles"""

def grabPublishDate(dataclips):
    data = requests.get(dataclips).json()
    values = data['values']
    #I should be using a list comprehension here
    holder = []
    for row in range(len(values)):
        holder.append(list(values[row][0].split(",")))
        # print split_value[0][1:]
        # print split_value[1]
    # print holder[0][0][1:]
    # test = holder[0][1].split(" ")
    # print holder[0][1]
    # print test[0][1:]
    return holder

def get_service(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

#I CHANGED THE PAGE PATH TO URL SO WE CAN PASS THE FIRST CELL OF THE CSV AS THE PAGEPATH

def get_results_thirty(service, profile_id,slug,publish_date):
    """Returns a simple iterable of requested GA data"""
    fixed_date = publish_date
    #datetime.datetime.strptime(publish_date, '%m/%d/%y').strftime('%Y-%m-%d')
    #Gets the right date format
    end_date = str((datetime.datetime.strptime(fixed_date, '%Y-%m-%d') + datetime.timedelta(days=int(sys.argv[2]))).date())
    #adds 30 days
    fixed_end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d').strftime('%Y-%m-%d')
    #converts to time back to a string
    output = service.data().ga().get(
      ids='ga:' + profile_id,
      start_date= fixed_date,
      end_date= fixed_end_date,
      metrics='ga:users',
      dimensions='ga:pagePath',
      filters='ga:pagePath=@' + '/' + sys.argv[3] + '/' + slug).execute()

    #pprint.pprint(output)
    return output

#GA in pseudo code should say:
#def function(row[0], row[1], End):
#ask for users? pageviews? both? for ga:pagePath, using URL to filter and Start
#or End as the start and end dates.
#get(ids=*, start_date='row[1]', end_date=*, metrics='ga:users', max_results=None, filters='ga:pagePath=row[0]', dimensions='ga:pagePath', sort=None, samplingLevel=None, segment=None, start_index=None, output=None)
def get_first_profile_id(service):
  # Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for the authorized user.
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[3].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()

      if profiles.get('items'):
        # return the first view (profile) id.
        return profiles.get('items')[0].get('id')
  return None

def initialize_service():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']
  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, 'client_secrets.json')
  profile = get_first_profile_id(service)
  return service, profile

def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'Total users: %s' % results.get('rows')[0][1]

  else:
    print 'No results found'

def main():
    service, profile = initialize_service()
    outputfile = open('output_articles_performance.csv', 'w')
    writer = csv.writer(outputfile)
    #holder = list(reversed(grabPublishDate(articles)))
    with open(sys.argv[1], 'rU') as inputfile:
        holder = list(csv.reader(inputfile))
        for row in range(len(holder)):
            #take the first and second cells of each row and hit GA
            date = holder[row][1].split(" ")
            #print_results(get_results_thirty(service, profile,holder[row][0][1:],date[row][1:]))
            try:
                ga_data = get_results_thirty(service,profile,holder[row][0],date[0])
                writer.writerow([holder[row][0],date[0],ga_data.get('rows')[0][1]])
                print holder[row][0], ga_data.get('rows')[0][1]
            except TypeError:
                continue
            except HttpError, error:
                sleep(3)
                continue


if __name__ == '__main__':
  main()
