# Copyright (c) 2001, 2002 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

__version__ = "$Revision: 2355 $"

from Thuban import _

from messages import EXTENSION_CHANGED, EXTENSION_OBJECTS_CHANGED

from base import TitledObject, Modifiable


class Extension(TitledObject, Modifiable):

    """Represent a extension. A extension is a package of additional
       functionality to Thuban and contains a number of Objects
       that can be freely defined in an extension.
       Each object must a a TitleObject with additional set "object.name".
       Furthermore, each object must implement the methods Subscribe,
       Unsubscribe and Destroy (i.e. derive from Modifiable).

    Extension objects send the following message types:

        EXTENSION_CHANGED -- Something in the extension has changed.

        EXTENSION_OBJECTS_CHANGED -- Something in the objects has changed.

    """

    forwarded_channels = (EXTENSION_CHANGED, EXTENSION_OBJECTS_CHANGED)

    def __init__(self, title):
        """Initialize the extension."""
        TitledObject.__init__(self, title)
        self.objects = []

    def Destroy(self):
        for object in self.objects:
            object.Destroy()
        Modifiable.Destroy(self)

    def AddObject(self, object):
        self.objects.append(object)
        for channel in self.forwarded_channels:
            object.Subscribe(channel, self.forward, channel)
        self.changed(EXTENSION_OBJECTS_CHANGED, self)

    def RemoveObject(self, object):
        for channel in self.forwarded_channels:
            object.Unsubscribe(channel, self.forward, channel)
        self.layers.remove(layer)
        self.changed(EXTENSION_OBJECTS_CHANGED, self)
        object.Destroy()

    def Objects(self):
        return self.objects

    def HasObjects(self):
        return len(self.objects) > 0

    def FindObject(self, title):
        """Find an object by title. If found, return it, else return None."""
        for object in self.objects:
            if object.title == title:
                return object
        return None

    def forward(self, *args):
        """Reissue events"""
        if len(args) > 1:
            args = (args[-1],) + args[:-1]
        apply(self.issue, args)

    def WasModified(self):
        """Return true if something of the extension was modified"""
        if self.modified:
            return 1
        else:
            return 0

    def UnsetModified(self):
        """Unset the modified flag of the extension"""
        Modifiable.UnsetModified(self)

    def TreeInfo(self):
        return (_("Extension: %s") % self.title,
                ["%s: %s" % (object.title, object.name)
                 for object in self.objects])
