# Path: performanceplatform/utils/data_parser.py
# class DataParser(object):
#     def __init__(self, data, options, data_type):
#         # it would be nice to have some json schemas or something to validate
#         # for now here are some docs
#         """
#         data: Can be any array of dicts
#         options: {
#           mappings: "a dict: converts keys matching key of the mappings dict
#               to the value in the mapping dict",
#           additionalFields: "a dict:
#               key value pairs will be added into the returned data",
#           idMapping: "a list of keys or single key string: for each key
#               the corresponding values will be concatenated in order to create
#               a unique _humanId field on the returned data and base64
#               encoded in order to create an _id field. If no idMapping
#               are provided then the item start_date and any avaiable
#               'dimensions' will be used instead",
#           dataType: "a value to be set on a dataType attribute.
#               Overrides the data_type argument"
#           plugins: "a list of string respresentations of python classes being
#               instantiated. e.g. ComputeIdFrom('_timestamp', '_timespan').
#               To be run on the passed in data to mutate it.
#               See performanceplatform.collector.ga.plugins for more details"
#         }
#         data_type: "a string - the data_type to be set as a data_type
#             attribute on the returned data unless it is overridden in options"
#         """
#         self.data = list(data)
#         if "plugins" in options:
#             self.plugins = options["plugins"]
#         else:
#             self.plugins = None
#         self.data_type = options.get('dataType', data_type)
#         self.mappings = options.get("mappings", {})
#         self.idMapping = options.get("idMapping", None)
#         self.additionalFields = options.get('additionalFields', {})
# 
#     def get_data(self, special_fields=None):
#         """
#         special_fields: "a dict of data specific to collector type
#             that should be added to the data returned by the parser.
#             This will also be and operated on by idMapping, mappings and
#             plugins"
# 
#         This method loops through the data provided to the instance.
#         For each item it will return a dict of the format:
#         {
#             "_timestamp": "the item start_date",
#             "dataType": "self.data_type for the instance",
#             ...
#             "any additional fields": "from self.additionalFields",
#             "any special_fields": "from special fields argument",
#             "any item dimensions": "from item.dimensions",
#             ...
#             mappings changing keys in this dict from self.mappings
#                are then applied on the above
#             ...
#             "_humanId": "derived from either the values corresponding to
#                idMapping concatenated or the data_type, item.start_date,
#                timeSpan and item.dimensions values if any concatenated"
#             "_id": "derived from either the values corresponding to
#                idMapping concatenated or the data_type, item.start_date,
#                timeSpan and item.dimensions values if any concatenated and
#                then base64 encoded"
#         }
#         """
#         docs = build_document_set(self.data, self.data_type, self.mappings,
#                                   special_fields,
#                                   self.idMapping,
#                                   additionalFields=self.additionalFields)
# 
#         if self.plugins:
#             docs = run_plugins(self.plugins, list(docs))
# 
#         return docs
# 
# Path: performanceplatform/utils/datetimeutil.py
# def period_range(start, end, frequency):
#     start_date = to_date(start)
#     end_date = to_date(end)
#     if start_date > end_date:
#         raise ValueError("Bad dates: !(start_date={0} <= end_date={1})"
#                          .format(start_date, end_date))
#     if frequency == 'daily':
#         start_date = start_date or a_day_ago()
#         end_date = end_date or a_day_ago()
#         period = timedelta(days=1)
#         return generate_date_range(start_date, end_date, period)
#     elif frequency == 'weekly':
#         start_date = start_date or a_week_ago()
#         start_date = start_of_week(start_date)
#         end_date = end_date or a_week_ago()
#         period = timedelta(days=7)
#         return generate_date_range(start_date, end_date, period)
#     elif frequency == 'monthly':
#         start_date = start_date or a_month_ago()
#         start_date = start_of_month(start_date)
#         end_date = end_date or a_month_ago()
#         period = relativedelta(months=+1)
#         return generate_date_range(start_date, end_date, period)
#     else:
#         raise ValueError('Bad value of frequency, should be daily, weekly '
#                          'or monthly')


import json
import logging
from performanceplatform.utils.data_parser import DataParser
from performanceplatform.utils.datetimeutil \
    import period_range



def query_ga(client, config, start_date, end_date):
    logging.info("Querying GA for data in the period: %s - %s"
                 % (str(start_date), str(end_date)))

    # If maxResults is 0, don't include it in the query.
    # Same for a sort == [].

    maxResults = config.get("maxResults", None)
    if maxResults == 0:
        maxResults = None

    sort = config.get("sort", None)
    if sort == []:
        sort = None

    return client.query.get(
        config["id"].replace("ga:", ""),
        start_date,
        end_date,
        config["metrics"],
        config.get("dimensions"),
        config.get("filters"),

# Path: performanceplatform/utils/data_parser.py
# class DataParser(object):
#     def __init__(self, data, options, data_type):
#         # it would be nice to have some json schemas or something to validate
#         # for now here are some docs
#         """
#         data: Can be any array of dicts
#         options: {
#           mappings: "a dict: converts keys matching key of the mappings dict
#               to the value in the mapping dict",
#           additionalFields: "a dict:
#               key value pairs will be added into the returned data",
#           idMapping: "a list of keys or single key string: for each key
#               the corresponding values will be concatenated in order to create
#               a unique _humanId field on the returned data and base64
#               encoded in order to create an _id field. If no idMapping
#               are provided then the item start_date and any avaiable
#               'dimensions' will be used instead",
#           dataType: "a value to be set on a dataType attribute.
#               Overrides the data_type argument"
#           plugins: "a list of string respresentations of python classes being
#               instantiated. e.g. ComputeIdFrom('_timestamp', '_timespan').
#               To be run on the passed in data to mutate it.
#               See performanceplatform.collector.ga.plugins for more details"
#         }
#         data_type: "a string - the data_type to be set as a data_type
#             attribute on the returned data unless it is overridden in options"
#         """
#         self.data = list(data)
#         if "plugins" in options:
#             self.plugins = options["plugins"]
#         else:
#             self.plugins = None
#         self.data_type = options.get('dataType', data_type)
#         self.mappings = options.get("mappings", {})
#         self.idMapping = options.get("idMapping", None)
#         self.additionalFields = options.get('additionalFields', {})
# 
#     def get_data(self, special_fields=None):
#         """
#         special_fields: "a dict of data specific to collector type
#             that should be added to the data returned by the parser.
#             This will also be and operated on by idMapping, mappings and
#             plugins"
# 
#         This method loops through the data provided to the instance.
#         For each item it will return a dict of the format:
#         {
#             "_timestamp": "the item start_date",
#             "dataType": "self.data_type for the instance",
#             ...
#             "any additional fields": "from self.additionalFields",
#             "any special_fields": "from special fields argument",
#             "any item dimensions": "from item.dimensions",
#             ...
#             mappings changing keys in this dict from self.mappings
#                are then applied on the above
#             ...
#             "_humanId": "derived from either the values corresponding to
#                idMapping concatenated or the data_type, item.start_date,
#                timeSpan and item.dimensions values if any concatenated"
#             "_id": "derived from either the values corresponding to
#                idMapping concatenated or the data_type, item.start_date,
#                timeSpan and item.dimensions values if any concatenated and
#                then base64 encoded"
#         }
#         """
#         docs = build_document_set(self.data, self.data_type, self.mappings,
#                                   special_fields,
#                                   self.idMapping,
#                                   additionalFields=self.additionalFields)
# 
#         if self.plugins:
#             docs = run_plugins(self.plugins, list(docs))
# 
#         return docs
# 
# Path: performanceplatform/utils/datetimeutil.py
# def period_range(start, end, frequency):
#     start_date = to_date(start)
#     end_date = to_date(end)
#     if start_date > end_date:
#         raise ValueError("Bad dates: !(start_date={0} <= end_date={1})"
#                          .format(start_date, end_date))
#     if frequency == 'daily':
#         start_date = start_date or a_day_ago()
#         end_date = end_date or a_day_ago()
#         period = timedelta(days=1)
#         return generate_date_range(start_date, end_date, period)
#     elif frequency == 'weekly':
#         start_date = start_date or a_week_ago()
#         start_date = start_of_week(start_date)
#         end_date = end_date or a_week_ago()
#         period = timedelta(days=7)
#         return generate_date_range(start_date, end_date, period)
#     elif frequency == 'monthly':
#         start_date = start_date or a_month_ago()
#         start_date = start_of_month(start_date)
#         end_date = end_date or a_month_ago()
#         period = relativedelta(months=+1)
#         return generate_date_range(start_date, end_date, period)
#     else:
#         raise ValueError('Bad value of frequency, should be daily, weekly '
#                          'or monthly')


# Path: performanceplatform/collector/ga/core.py
import json
import logging
from performanceplatform.utils.data_parser import DataParser
from performanceplatform.utils.datetimeutil \
    import period_range




def query_ga(client, config, start_date, end_date):
    logging.info("Querying GA for data in the period: %s - %s"
                 % (str(start_date), str(end_date)))

    # If maxResults is 0, don't include it in the query.
    # Same for a sort == [].

    maxResults = config.get("maxResults", None)
    if maxResults == 0:
        maxResults = None

    sort = config.get("sort", None)
    if sort == []:
        sort = None

    return client.query.get(
        config["id"].replace("ga:", ""),
        start_date,
        end_date,
        config["metrics"],
        config.get("dimensions"),
        config.get("filters"),

        maxResults,