# -*- 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 2.
# 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.service_provider import ServiceProvider
from elisa.core.component import InitializeFailure
from elisa.core import common
from elisa.core.epm import egg_registry

from twisted.internet import defer, reactor

plugin_registry = common.application.plugin_registry
ElisaUpdateMessage = plugin_registry.get_component_class('updater:elisa_update_message')

class UpdaterService(ServiceProvider):
    """
    Elisa service able to periodically scan the Elisa Plugin
    Repository and find potential updates of the installed plugins.
    """
    
    default_config = {'update_interval': 86400,
                      }
    
    config_doc = {'update_interval': 'timerange in seconds between 2 '\
                                     'refreshes of the plugins cache',
                  }
                  
    def initialize(self):
        self._registry = egg_registry.EggRegistry()
        self._delayed_call = None
        self._update_interval = int(self.config.get('update_interval', '86400'))

        # for test purpose
        common.application.bus.register(self._msg_received,
                                        (ElisaUpdateMessage,))
        
    def start(self):
        self._schedule_new_cache_update(None, 1)

    def stop(self):
        if self._delayed_call is not None:
            self._delayed_call.cancel()

    def _msg_received(self, msg, sender):
        print msg.upgradeable_plugins
        
    def _got_upgradeables(self, upgradeables):
        msg = ElisaUpdateMessage(upgradeables)
        common.application.bus.send_message(msg)

    def _check_upgrades(self, result):
        # FIXME: move out maybeDeferred when get_upgradeable_plugins
        #        returns a real deferred
        dfr = defer.maybeDeferred(self._registry.get_upgradeable_plugins,
                                  ['important'])
        dfr.addCallback(self._got_upgradeables)
        return dfr

    def _update_cache(self):
        dfr = self._registry.update_cache()
        dfr.addCallback(self._check_upgrades)
        dfr.addCallback(self._schedule_new_cache_update, self._update_interval)

    def _schedule_new_cache_update(self, dummy, interval):
        self.info("New plugins cache update will happen in %r seconds",
                  interval)
        self._delayed_call = reactor.callLater(interval, self._update_cache)
