# Path: invenio_stats/utils.py
# def get_anonymization_salt(ts):
#     """Get the anonymization salt based on the event timestamp's day."""
#     salt_key = 'stats:salt:{}'.format(ts.date().isoformat())
#     salt = current_cache.get(salt_key)
#     if not salt:
#         salt_bytes = os.urandom(32)
#         salt = b64encode(salt_bytes).decode('utf-8')
#         current_cache.set(salt_key, salt, timeout=60 * 60 * 24)
#     return salt
# 
# def get_doctype(doc_type):
#     """Configure doc_type value according to ES version."""
#     return doc_type if ES_VERSION[0] < 7 else '_doc'
# 
# def get_geoip(ip):
#     """Lookup country for IP address."""
#     reader = geolite2.reader()
#     ip_data = reader.get(ip) or {}
#     return ip_data.get('country', {}).get('iso_code')
# 
# def obj_or_import_string(value, default=None):
#     """Import string or return object.
# 
#     :params value: Import path or class object to instantiate.
#     :params default: Default object to return if the import fails.
#     :returns: The imported object.
#     """
#     if isinstance(value, six.string_types):
#         return import_string(value)
#     elif value:
#         return value
#     return default


import hashlib
import elasticsearch
from time import mktime
from counter_robots import is_machine, is_robot
from dateutil import parser
from flask import current_app
from invenio_search import current_search_client
from invenio_search.utils import prefix_index
from pytz import utc
from .utils import get_anonymization_salt, get_doctype, get_geoip, \
    obj_or_import_string
from __future__ import absolute_import, print_function





def anonymize_user(doc):
    """Preprocess an event by anonymizing user information.

    The anonymization is done by removing fields that can uniquely identify a
    user, such as the user's ID, session ID, IP address and User Agent, and
    hashing them to produce a ``visitor_id`` and ``unique_session_id``. To
    further secure the method, a randomly generated 32-byte salt is used, that
    expires after 24 hours and is discarded. The salt values are stored in
    Redis (or whichever backend Invenio-Cache uses). The ``unique_session_id``
    is calculated in the same way as the ``visitor_id``, with the only
    difference that it also takes into account the hour of the event . All of
    these rules effectively mean that a user can have a unique ``visitor_id``
    for each day and unique ``unique_session_id`` for each hour of a day.

    This session ID generation process was designed according to the `Project
    COUNTER Code of Practice <https://www.projectcounter.org/code-of-
    practice-sections/general-information/>`_.

    In addition to that the country of the user is extracted from the IP
    address as a ISO 3166-1 alpha-2 two-letter country code (e.g. "CH" for
    Switzerland).
    """
    ip = doc.pop('ip_address', None)
    if ip:

# Path: invenio_stats/utils.py
# def get_anonymization_salt(ts):
#     """Get the anonymization salt based on the event timestamp's day."""
#     salt_key = 'stats:salt:{}'.format(ts.date().isoformat())
#     salt = current_cache.get(salt_key)
#     if not salt:
#         salt_bytes = os.urandom(32)
#         salt = b64encode(salt_bytes).decode('utf-8')
#         current_cache.set(salt_key, salt, timeout=60 * 60 * 24)
#     return salt
# 
# def get_doctype(doc_type):
#     """Configure doc_type value according to ES version."""
#     return doc_type if ES_VERSION[0] < 7 else '_doc'
# 
# def get_geoip(ip):
#     """Lookup country for IP address."""
#     reader = geolite2.reader()
#     ip_data = reader.get(ip) or {}
#     return ip_data.get('country', {}).get('iso_code')
# 
# def obj_or_import_string(value, default=None):
#     """Import string or return object.
# 
#     :params value: Import path or class object to instantiate.
#     :params default: Default object to return if the import fails.
#     :returns: The imported object.
#     """
#     if isinstance(value, six.string_types):
#         return import_string(value)
#     elif value:
#         return value
#     return default


# Path: invenio_stats/processors.py
import hashlib
import elasticsearch
from time import mktime
from counter_robots import is_machine, is_robot
from dateutil import parser
from flask import current_app
from invenio_search import current_search_client
from invenio_search.utils import prefix_index
from pytz import utc
from .utils import get_anonymization_salt, get_doctype, get_geoip, \
    obj_or_import_string

from __future__ import absolute_import, print_function





def anonymize_user(doc):
    """Preprocess an event by anonymizing user information.

    The anonymization is done by removing fields that can uniquely identify a
    user, such as the user's ID, session ID, IP address and User Agent, and
    hashing them to produce a ``visitor_id`` and ``unique_session_id``. To
    further secure the method, a randomly generated 32-byte salt is used, that
    expires after 24 hours and is discarded. The salt values are stored in
    Redis (or whichever backend Invenio-Cache uses). The ``unique_session_id``
    is calculated in the same way as the ``visitor_id``, with the only
    difference that it also takes into account the hour of the event . All of
    these rules effectively mean that a user can have a unique ``visitor_id``
    for each day and unique ``unique_session_id`` for each hour of a day.

    This session ID generation process was designed according to the `Project
    COUNTER Code of Practice <https://www.projectcounter.org/code-of-
    practice-sections/general-information/>`_.

    In addition to that the country of the user is extracted from the IP
    address as a ISO 3166-1 alpha-2 two-letter country code (e.g. "CH" for
    Switzerland).
    """
    ip = doc.pop('ip_address', None)
    if ip:

        doc.update({'country': get_geoip(ip)})