# -*- 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__ = 'Benjamin Kampmann <benjamin@fluendo.com>'

from menu_entry_builder import MenuEntryBuilder
from elisa.core.plugin_registry import PluginNotFound, ComponentNotFound

from elisa.core import common

from twisted.internet import defer

class ActivityNodeBuilder(MenuEntryBuilder):

    def menu_entry_identifiers__get(self):
        return ['activity_node']

    def build_menu_entry(self, parent, node_xml):
        registry = common.application.plugin_registry

        a_xml = node_xml.find('Activity')

        if a_xml == None:
            self.warning("Missing 'Activity'-Tag in %s" % node_xml)
            return defer.succeed([])

        activity_path = a_xml.text

        registry = common.application.plugin_registry
        try:
            # FIXME: this should be Deferred-Based!
            activity = registry.create_component(activity_path)
        except (PluginNotFound, ComponentNotFound), error:
            self.warning("Could not make activity %s:%s" % (activity_path,
                                error))
            return defer.succeed([])
        else:
            # I don't like that!
            activity.player_model = parent.activity.player_model

        model_class = registry.get_component_class('base:menu_node_model')
        
        # works only, if we can be sure, that we get an MenuNode-Model
        # from the acvtivity!
        model = activity.get_model()

        if not isinstance(model, model_class):
            parent_model = registry.create_component('base:menu_node_model')
            parent_model.text = self._make_label(node_xml.find('Label'))
            self._set_icon(parent_model, node_xml.find('Icon'))
            # FIXME: this should better be a action that returns the other
            # model, but actions do not yet return models.
            # parent_model.action = model 
            return defer.succeed([parent_model])
        else:
            parent.children.append(model)
            return defer.succeed([model])


