# This module was copied almost verbatim from Sketch. The only change is
# the base class of ConnectorError which was a Sketch specific exception
# class. 

# Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 2000, 2001, 2003 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

__version__ = "$Revision: 1.7 $"

#
#       The Connector
#

import sys
from types import MethodType

from Thuban import _

class ConnectorError(Exception):
    pass

class Connector:

    def __init__(self):
        self.connections = {}

    def Connect(self, object, channel, function, args):
        idx = id(object)
        if self.connections.has_key(idx):
            channels = self.connections[idx]
        else:
            channels = self.connections[idx] = {}

        if channels.has_key(channel):
            receivers = channels[channel]
        else:
            receivers = channels[channel] = []

        info = (function, args)
        try:
            receivers.remove(info)
        except ValueError:
            pass
        receivers.append(info)

    def Disconnect(self, object, channel, function, args):
        try:
            receivers = self.connections[id(object)][channel]
        except KeyError:
            raise ConnectorError, \
                  _('no receivers for channel %s of %s') % (channel, object)
        try:
            receivers.remove((function, args))
        except ValueError:
            raise ConnectorError,\
            _('receiver %s%s is not connected to channel %s of %s') \
            % (function, args, channel, object)

        if not receivers:
            # the list of receivers is empty now, remove the channel
            channels = self.connections[id(object)]
            del channels[channel]
            if not channels:
                # the object has no more channels
                del self.connections[id(object)]

    def Issue(self, object, channel, *args):
        #print object, channel, args
        try:
            receivers = self.connections[id(object)][channel]
        except KeyError:
            return
        # Iterate over a copy of receivers because the receivers might
        # unsubscribe themselves when receiving a message and Disconnect
        # would modify receivers in place while we're iterating over it.
        for func, fargs in receivers[:]:
            try:
                apply(func, args + fargs)
            except:
                sys.stderr.write(_("Warning: %s.%s: %s%s\n")
                                 % (object, channel, func, fargs))
                import traceback
                traceback.print_exc()

    def RemovePublisher(self, object):
        i = id(object)
        if self.connections.has_key(i):
            del self.connections[i]
        # don't use try: del ... ; except KeyError here. That would create a
        # new reference of object in a traceback object and this method should
        # be callable from a __del__ method (at least for versions prior
        # Python 1.5)

    def HasSubscribers(self, object):
        return self.connections.has_key(id(object))

    def print_connections(self):
        # for debugging
        for id, channels in self.connections.items():
            for name, subscribers in channels.items():
                print hex(id), name
                for func, args in subscribers:
                    if type(func) == MethodType:
                        print _('\tmethod %s of %s') % (func.im_func.func_name,
                                                        func.im_self)
                    else:
                        print '\t', func



_the_connector = Connector()

Connect = _the_connector.Connect
Issue = _the_connector.Issue
RemovePublisher = _the_connector.RemovePublisher
Disconnect = _the_connector.Disconnect
def Subscribe(channel, function, *args):
    return Connect(None, channel, function, args)


class Publisher:

    # Flag indicating whether the publisher instance was destroyed.
    _was_destroyed = False

    def __del__(self):
        # the new finalization code in 1.5.1 might bind RemovePublisher
        # to None before all objects derived from Publisher are deleted...
        if RemovePublisher is not None:
            RemovePublisher(self)

    def Subscribe(self, channel, func, *args):
        Connect(self, channel, func, args)

    def Unsubscribe(self, channel, func, *args):
        """Unsubscribe from the channel.

        If the publisher's Destroy method has been called already, do
        nothing, because the subscriptions will already have been
        removed in Destroy and trying to disconnect it here will lead to
        exceptions.
        """
        if not self._was_destroyed:
            Disconnect(self, channel, func, args)

    def issue(self, channel, *args):
        apply(Issue, (self, channel,) + args)

    def Destroy(self):
        """Remove all subscriptions of messages sent by self."""
        RemovePublisher(self)
        self._was_destroyed = True


class Conduit(Publisher):

    def _do_forward(self, *args, **kw):
        self.issue(args[-1], *args[:-1], **kw)

    def subscribe_forwarding(self, channel, obj):
        if obj is not None:
            obj.Subscribe(channel, self._do_forward, channel)

    def unsubscribe_forwarding(self, channel, obj):
        if obj is not None:
            obj.Unsubscribe(channel, self._do_forward, channel)

