""" Helper module for Google Analytics pandas integration.
    Uses authentication with a service account (see
    developers.google.com/api-client-library/python/auth/service-accounts),
    without the need of a ``client_secrets.json`` file. Client email and
    private key must be provided as environment variables. The private key was
    generated by converting the p12 to pem using openssl.

"""
from flask import current_app as app
from httplib2 import Http
from oauth2client.client import SignedJwtAssertionCredentials
import pandas.io.auth as auth
from pandas.io.ga import GAnalytics


class ResmioGAnalytics(GAnalytics):

    def __init__(self, client_email, private_key, scope):
        self.client_email = client_email
        self.private_key = private_key
        self.scope = scope
        self._service = self._init_service()

    def _init_service(self):
        credentials = SignedJwtAssertionCredentials(
            self.client_email, self.private_key, self.scope)
        http = Http()
        http = credentials.authorize(http)
        return auth.init_service(http)


def get_ga_reader():
    return ResmioGAnalytics(app.config.get('GA_CLIENT_EMAIL'),
                            app.config.get('GA_PRIVATE_KEY'),
                            app.config.get('GA_SCOPE'))
