# -*- 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.
#
# Author: Florian Boucault <florian@fluendo.com>

from elisa.core.manager import Manager

from twisted.internet import defer
from warnings import warn

def call_on_component(component, attr):
    # deprecated
    if hasattr(component, attr):
        warn("ServiceProvider.%s is deprecated." % attr, DeprecationWarning)
        try:
            return getattr(component, attr)()
        except Exception, error:
            return defer.fail(error)
    return defer.succeed(None)

class ServiceManager(Manager):

    """
    Manage a list of service providers.
    """

    entry_point = 'elisa.core.components.service_provider'

    def register_component(self, component):
        dfr = super(ServiceManager, self).register_component(component)
        # When registering a new service provider, we want to start it.
        dfr.addCallback(call_on_component, 'start')
        return dfr

    def unregister_component(self, component):
        dfr = super(ServiceManager, self).unregister_component(component)
        dfr.addCallback(call_on_component, 'stop')
        return dfr
