# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
#     """ A version of open with an exclusive lock to be used within
#         controlled execution statements.
#     """
#     def __init__(self, *args, **kwargs):
#         super(open_locked, self).__init__(*args, **kwargs)
#         fcntl.flock(self, fcntl.LOCK_EX)
# 
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')


import os
import time
import json
from uuid import uuid1, uuid5
from kano.utils.file_operations import chown_path, touch
from kano.logging import logger
from kano_profile.tracker.tracking_utils import open_locked
from kano_profile.paths import TRACKER_UUIDS_PATH

    Returns:
        dict: A uuid object if one is found or an empty dict otherwise.
    """

    uuids_file, data = _open_uuids()
    uuids_file.close()

    return data.get(key, dict())


def _add_tracking_uuid(key, tracking_uuid):
    """Store a new uuid object.

    Args:
        key (str): The namespace associated with a uuid, e.g. 'kano-tracker-ctl'.
    """

    uuids_file, data = _open_uuids()
    if not uuids_file:
        logger.error('Could not store tracking uuid!')
        return

    with uuids_file:
        data[key] = tracking_uuid
        uuids_file.seek(0)
        uuids_file.truncate(0)
        uuids_file.write(json.dumps(data))

    if 'SUDO_USER' in os.environ:

# Path: kano_profile/tracker/tracking_utils.py
# class open_locked(file):
#     """ A version of open with an exclusive lock to be used within
#         controlled execution statements.
#     """
#     def __init__(self, *args, **kwargs):
#         super(open_locked, self).__init__(*args, **kwargs)
#         fcntl.flock(self, fcntl.LOCK_EX)
# 
# Path: kano_profile/paths.py
# TRACKER_UUIDS_PATH = os.path.join(kanoprofile_dir, 'tracker', 'uuids')


# Path: kano_profile/tracker/tracking_uuids.py
import os
import time
import json
from uuid import uuid1, uuid5
from kano.utils.file_operations import chown_path, touch
from kano.logging import logger
from kano_profile.tracker.tracking_utils import open_locked
from kano_profile.paths import TRACKER_UUIDS_PATH


    Returns:
        dict: A uuid object if one is found or an empty dict otherwise.
    """

    uuids_file, data = _open_uuids()
    uuids_file.close()

    return data.get(key, dict())


def _add_tracking_uuid(key, tracking_uuid):
    """Store a new uuid object.

    Args:
        key (str): The namespace associated with a uuid, e.g. 'kano-tracker-ctl'.
    """

    uuids_file, data = _open_uuids()
    if not uuids_file:
        logger.error('Could not store tracking uuid!')
        return

    with uuids_file:
        data[key] = tracking_uuid
        uuids_file.seek(0)
        uuids_file.truncate(0)
        uuids_file.write(json.dumps(data))

    if 'SUDO_USER' in os.environ:

        chown_path(TRACKER_UUIDS_PATH)