# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2007-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.components.service_provider import ServiceProvider
from elisa.core import common
from elisa.core.log import Loggable
from elisa.core.utils.misc import is_hildon_desktop_running

from elisa.plugins.pigment.pigment_frontend import PigmentFrontend

import dbus
import dbus.glib
import dbus.service

from twisted.internet import defer


class OssoDbusService(dbus.service.Object, Loggable): 
    """ 
    DBus service used to restore Elisa window when user taps on elisa
    launcher, in case of Elisa has already been started but its window
    is not visible anymore (ex: another window comes on top of it).
    
    """
    
    def __init__(self):
        self.name = 'com.fluendo.elisa'
        self.path = '/com/fluendo/elisa'
        bus_name = dbus.service.BusName(self.name, bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, self.path)
        Loggable.__init__(self)

    @dbus.service.method(dbus_interface='com.fluendo.elisa',
            in_signature='', out_signature='')
    def top_application(self):
        # FIXME: implement this properly without hardcoding pigment stuff
        self.debug('top application')
        interface_controller = common.application.interface_controller
        for name, frontend in interface_controller.frontends.iteritems():
            self.debug('update frontend %s', name)
            if isinstance(frontend, (PigmentFrontend,)):
                if frontend.gtk_window is not None:
                    frontend.gtk_window.present()
                else:
                    frontend.viewport_handle.visible = False
                    frontend.viewport_handle.visible = True
            self.debug('updated frontend %s', name)


class OssoService(ServiceProvider):
    def initialize(self):
        self.debug('service initialize')
        if not is_hildon_desktop_running():
            return defer.fail(RuntimeError('hildon not running'))

        self._osso_service = OssoDbusService()
        return defer.succeed(self)

    def clean(self):
        self._osso_service = None
        return super(OssoService, self).clean()
