# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).

__all__ = ['SCOPES', 'KEY_FILE_LOCATION', 'credentials', 'ga_to_df']

# Cell

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

import os
from dotenv import load_dotenv
import pandas as pd
load_dotenv()

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')

credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)

# Cell


def ga_to_df(start_date: str, end_date: str, metrics: list, dimensions: list, filters: list = None, view_id = None) -> pd.DataFrame:
    if not view_id:
        view_id = os.getenv('GOOGLE_ANALYTICS_VIEW_ID')
    qry = {
        'dateRanges': [{'startDate': start_date, 'endDate': end_date}],
        'metrics': [{'expression': m} for m in metrics],
        'dimensions': [{'name': m} for m in dimensions],
    }
    if filters:
        qry['dimensionFilterClauses'] = [
            {'operator': f[0], 'filters': [{'dimensionName': f[1][0], 'operator': f[1][1], 'expressions': f[1][2]}]}
            for f in filters
        ]
    qry['viewId'] = view_id
    analytics = build('analyticsreporting', 'v4', credentials=credentials)
    request_list = [qry]
    response = analytics.reports().batchGet(body={'reportRequests': request_list}).execute()
    data = []
    for report in response.get('reports'):
        dimensions = report.get('columnHeader').get('dimensions')
        metrics = [x['name'] for x in report.get('columnHeader').get('metricHeader').get('metricHeaderEntries')]
        for row in report.get('data').get('rows'):
            dimensions_data = row.get('dimensions', [])
            metrics_data = [x['values'] for x in row.get('metrics', [])][0]
            metrics_data = [float(x) for x in metrics_data]
            colnames = dimensions + metrics
            data_row = dimensions_data + metrics_data
            data.append(data_row)
    df = pd.DataFrame(data, columns=colnames)
    return df

