# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.

"""
Notifying dictionary.
"""

import gobject


class Notifier(gobject.GObject):

    """
    A notifier that emits an items-changed signal when its associated dictionary
    is updated.

    The items-changed signal is emitted with three parameters: the dictionary
    itself, the key of the modified item, the value of the modified item.
    """

    __gsignals__ = \
        {'items-changed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_PYOBJECT,
                          (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
        }

gobject.type_register(Notifier)


class NotifyingDictionary(dict):

    """
    A dictionary that emits a signal when items are set/modified.

    The signal is emitted through a L{Notifier} object.
    """

    # FIXME: incomplete: it does not override all the dict methods that write:
    # - setdefault
    # - clear
    # - pop
    # - popitem
    # - __delitem__
    #
    # cf. http://www.python.org/doc/2.5.2/lib/typesmapping.html

    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.notifier = Notifier()

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        self.notifier.emit('items-changed', self, {key: value})

    def update(self, other):
        dict.update(self, other)
        self.notifier.emit('items-changed', self, other)

    def __deepcopy__(self, memo):
        new_dict = self.__class__(self)
        return new_dict
