#-*- coding: utf-8 -*-

# Copyright 2014-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import dbus
import dbus.service
import dbus.mainloop.glib

DBUS_NAME = "org.calculate.consolegui"
DBUS_METHOD_APP = "/org/calculate/consolegui/%s"
DBUS_MAINAPP = "/org/calculate/consolegui/app"
DBUS_NAME_UPDATER = "org.calculate.updater"
DBUS_APP_UPDATER = "/org/calculate/updater"


class DBusWidget(dbus.service.Object):
    def __init__(self, name, session, parent):
        self._parent = parent
        # export this object to dbus
        dbus.service.Object.__init__(self, name, session)

    # You can export methods to dbus like you do in python-dbus.
    @dbus.service.method(DBUS_NAME, in_signature='', out_signature='')
    def show(self):
        self._parent.hide()
        debug(11, "DEBUG DBusWidget")
        self._parent.show()
        self._parent.showNormal()

    @dbus.service.method(DBUS_NAME, in_signature='', out_signature='')
    def update(self):
        from .ConnectionTabs import ToolTabWidget
        if isinstance(self._parent, ToolTabWidget):
            self._parent.tray.start_update_system()

    @dbus.service.method(DBUS_NAME, in_signature='', out_signature='b')
    def ping(self):
        return True


def dbus_updater_hide_tray(bus):
    """
    :param bus: SessionBus
    """
    try:
        remote_object = bus.get_object(DBUS_NAME_UPDATER, DBUS_APP_UPDATER)
        obj = dbus.Interface(remote_object, DBUS_NAME_UPDATER)
        if obj:
            obj.hide_systray()
    except dbus.DBusException:
        pass
