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

from elisa.core import common
from elisa.core.service_manager import ServiceManager
from elisa.core.components.service_provider import ServiceProvider
from elisa.core.utils import defer

from twisted.trial.unittest import TestCase


class SimpleService(ServiceProvider):
    running = False

    def start(self):
        self.running = True
        return defer.succeed(None)

    def stop(self):
        self.running = False
        return defer.succeed(None)


class BusMock(object):
    def register(self, callback, *message_types):
        pass

    def unregister(self, callback):
        pass


class ApplicationMock(object):
    bus = BusMock()


class TestServiceManager(TestCase):

    def setUp(self):
        self._patch_application()
        self._manager = ServiceManager()
        self._service = SimpleService()

    def tearDown(self):
        self._service = None
        self._manager = None
        self._unpatch_application()

    def _patch_application(self):
        self._old_application = common.application
        common.application = ApplicationMock()

    def _unpatch_application(self):
        common.application = self._old_application

    def _check_service_status(self, result, expected_status):
        self.failUnlessEqual(self._service.running, expected_status)

    def test_register_unregister_service(self):
        # Check that registering a service starts it, and unregistering it
        # stops it.
        dfr = self._manager.register_component(self._service)
        dfr.addCallback(self._check_service_status, True)
        dfr.addCallback(lambda result:
                        self._manager.unregister_component(self._service))
        dfr.addCallback(self._check_service_status, False)
        return dfr
