import collections
from datetime import datetime


class TimestampedDict(collections.UserDict):
    """
    A dictionary with additional metadata
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # NOQA

        self._last_modified = datetime.now()  # last time a value got modified
        self._last_added = datetime.now()  # last time a new value have been added

    def __setitem__(self, key, value):
        # if the key is already used, we only update a value
        update = key in self
        # set the value
        super().__setitem__(key, value)

        # update modification time
        self._last_modified = datetime.now()
        # if this is not an update, set the added time
        if not update:
            self._last_added = datetime.now()

    def __delitem__(self, key):
        super().__delitem__(key)
        self._last_modified = datetime.now()

    def update(self, *args, **kwargs):
        super().update(*args, **kwargs)  # NOQA
        self._last_modified = datetime.now()

    @property
    def last_modified(self):
        return self._last_modified

    @property
    def last_added(self):
        return self._last_added