"""

"""

from neoteric.util.debug import get_stack

class DuplicateResourceError(Exception):
    pass

class ResourceTracker:
    """ Each resource type should implement this class as a global
        variable to prevent duplicate resource definitions.

        To override properties of an existing object, retrieve it with
        ResourceTracker[key_name] and modify, or remove it with
        ResourceTracker.pop(key_name) and then instantiate a new resource

    """
    def __init__(self):
        self.resources = {}
        self.tb = {}

    def _clear(self):
        """ This is only meant to be used for testing,
            it is very unlikely that you would want to use
            this in real life
        """
        self.resources.clear()
        self.tb.clear()

    def pop(self, key):
        self.resources.pop(key)
        self.tb.pop(key)

    def __getitem__(self, key):
        return self.resources[key]

    def __setitem__(self, key, value):
        if key in self.resources:
            msg = "Duplicate resource definition: "\
                "{0} already defined as {1} "\
                "from (most recent call last):".format(key, self[key])
            msg += self.tb[key]
            value._has_actioned = True # suppress GC error messages
            raise DuplicateResourceError(msg)
        self.resources[key] = value
        self.tb[key] = get_stack()
