# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 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 Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

"""
"""

__maintainer__ = "Philippe Normand <philippe@fluendo.com>"

from elisa.base_components import service_provider
from elisa.core import common, component
from twisted.spread import pb
from twisted.internet import reactor
import new

class Root(pb.Root):
    pass

plugin_registry = common.application.plugin_registry
PBReferenceableMessage = plugin_registry.get_component_class('twisted:pbreferenceable_message')

class TwistedPBService(service_provider.ServiceProvider):
    """


    """

    default_config = {'port': '8789'}
    config_doc = {'port': 'TCP port to listen on'}

    def initialize(self):
        self.root = Root()
        port = int(self.config.get('port'))
        try:
            reactor.listenTCP(port, pb.PBServerFactory(self.root))
        except Exception, error:
            raise component.InitializeFailure(self.name,str(error))
        common.application.bus.register(self._register_new_reference,
                                        PBReferenceableMessage)

    def _register_new_reference(self, msg, sender):
        method_name = 'remote_%s' % msg.name
        func = lambda s: msg.reference
        func.__name__ =  method_name

        self.debug("Registering %r -> %r", method_name, func)
        method = new.instancemethod(func, self.root, Root)
        setattr(self.root, method_name, method)
