# -*- 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.

"""
UPnP MediaRenderer
"""

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

from elisa.base_components import service_provider
from elisa.core import common, component
from coherence.base import Coherence
import louie

plugin_registry = common.application.plugin_registry
CoherenceDeviceMessage = plugin_registry.get_component_class('coherence:coherence_device_message')
CoherencePluginMessage = plugin_registry.get_component_class('coherence:coherence_plugin_message')

class CoherenceService(service_provider.ServiceProvider):
    """

    """

    default_config = {'logmode':'warn',
                      'controlpoint': 'yes',
                      'plugins':{}}

    def initialize(self):
        coherence_config = self.config
        coherence_config['plugins'] = {}
        try:
            coherence_instance = Coherence(coherence_config)
        except Exception, coherence_exception:
            error = "Coherence failed to start. Error: %s" % coherence_exception
            raise component.InitializeFailure(self.name, error)
        self._coherence = coherence_instance
        common.application.bus.register(self._got_message,
                                        CoherencePluginMessage,
                                        CoherenceDeviceMessage)

    def _got_message(self, msg, sender):
        if isinstance(msg, CoherencePluginMessage):
            name = msg.name
            args = msg.args
            self.debug("Registering plugin %r", name)
            self._coherence.add_plugin(name, **args)
        else:
            louie.connect(msg.callback, msg.name, msg.typ)

    def stop(self):
        self._coherence.shutdown()
