#!/usr/bin/env python

import os
import argparse
import json
import re
import googleanalytics as ga


def normalize_identification(identification):
    client_secret = False
    name = ''

    if len(identification) == 3:
        name, client_id, client_secret = identification
    if len(identification) == 2:
        client_id, client_secret = identification
        name = client_id
    elif len(identification) == 1:
        client_id = os.environ
        name = identification[0]
    elif len(identification) == 0:
        if 'GOOGLE_ANALYTICS_CLIENT_ID' in os.environ \
            and 'GOOGLE_ANALYTICS_CLIENT_SECRET' in os.environ:
                client_id = os.environ
        else:
            name = raw_input('Human-readable account name: ')
            client_id = raw_input('Client ID: ')
            client_secret = raw_input('Client secret: ')
    else:
        raise ValueError()

    return dict(name=name, client_id=client_id, client_secret=client_secret)


def auth_command(arguments):
    identification = normalize_identification(arguments.identifiers)
    return ga.utils.keyring.ask_and_authenticate(**identification)


def revoke_command(arguments):
    return ga.utils.keyring.revoke(arguments.name)


def ls_command(arguments):
    """ analytics ls <name> <acc> <prop> <profile> <columnsearch> """

    identifiers = arguments.identifiers

    while len(identifiers) < 5:
        identifiers.append(None)

    name, account, webproperty, profile, pattern = identifiers
    tokens = ga.utils.keyring.get(name) or auth_command(name)
    accounts = ga.oauth.ask_and_authenticate(**tokens)

    def print_list(l):
        for item in l:
            print item

    def match(column):
        return re.search(pattern, column.name, re.IGNORECASE)

    if pattern:
        columns = accounts[account].columns
        filtered_columns = filter(match, columns)
        print_list(filtered_columns)
    elif profile:
        columns = accounts[account].columns
        print_list(columns)
    elif webproperty:
        profiles = accounts[account].webproperties[webproperty].profiles
        print_list(profiles)
    elif account:
        webproperties = accounts[account].webproperties
        print_list(webproperties)
    else:
        print_list(accounts)


arguments = argparse.ArgumentParser()
subparsers = arguments.add_subparsers()

auth = subparsers.add_parser('auth')
auth.set_defaults(func=auth_command, 
    help="authenticate with Google Analytics")
auth.add_argument('identifiers', nargs='*')

revoke = subparsers.add_parser('revoke')
revoke.add_argument('name', default='', nargs='?')
revoke.set_defaults(func=revoke_command, 
    help="revoke Google Analytics OAuth credentials")

ls = subparsers.add_parser('ls')
ls.add_argument('identifiers', default=[''], nargs='*')
ls.set_defaults(func=ls_command, 
    help="list Google Analytics accounts, web properties, profiles and data columns")


if __name__ == '__main__':
    args = arguments.parse_args()
    args.func(args)