#!/usr/bin/env python
#-*- coding: utf-8 -*-

# Copyright 2012-2013 Calculate Ltd. 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 os

from PySide import QtCore, QtGui
import time
from calculate.core.client.cert_info import user_can_run_update
import dbus
import dbus.service
import dbus.mainloop.glib
from calculate.lib.utils.tools import debug
from calculate.consolegui.application.dbus_service import (DBUS_NAME,
    DBUS_METHOD_APP, DBUS_MAINAPP, DBUS_APP_UPDATER, DBUS_NAME_UPDATER)

from calculate.update.update_info import UpdateInfo

GUI_UPDATE_APP = DBUS_METHOD_APP % "update"


class SysTray(QtGui.QSystemTrayIcon):
    ICON = "/usr/share/pixmaps/calculate-console-update.png"

    def __init__(self, parent):
        super(SysTray, self).__init__()
        self.parent = parent
        self.timeout = 0

        self.setIcon(QtGui.QIcon(self.ICON))

        self.activated.connect(self.systrayActivate)

    def run_cl_gui_update(self):
        cmd = '/usr/bin/cl-console-gui'
        method = "update"
        params = ["--skip-options"]
        os.system("{cmd} --method {method} {params} &>/dev/null &".format(
            cmd=cmd, method=method, params=" ".join(params)))

    def show_update(self):
        try:
            iface = self.parent.get_dbus_iface(GUI_UPDATE_APP)
            if iface:
                iface.show()
                return True
        except dbus.DBusException:
            return False
        return False

    def systrayActivate(self, reason):
        if time.time() > self.timeout:
            self.timeout = time.time() + 5
            self.show_update() or self.run_cl_gui_update()
            self.parent.step()


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

    @dbus.service.method(DBUS_NAME_UPDATER, in_signature='', out_signature='')
    def hide_systray(self):
        self.parent.systray.hide()

    @dbus.service.method(DBUS_NAME_UPDATER, in_signature='', out_signature='')
    def show_systray(self):
        self.parent.systray.show()

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

    @dbus.service.method(DBUS_NAME_UPDATER, in_signature='', out_signature='')
    def quit(self):
        QtGui.qApp.quit()

    @dbus.service.method(DBUS_NAME_UPDATER, in_signature='', out_signature='')
    def check(self):
        self.parent.step()

class CheckThread(QtGui.QMainWindow, UpdateInfo):
    interval = 10

    def __init__(self, bus):
        super(CheckThread, self).__init__()
        UpdateInfo.__init__(self)

        self.bus = bus
        self.already_timer = QtCore.QTimer(self)
        self.already_timer.timeout.connect(self.step_already)
        self.already_timer.start(1000)

        self.check_timer = QtCore.QTimer(self)
        self.check_timer.timeout.connect(self.step)
        self.check_timer.start(self.interval * 1000)

        self.systray = SysTray(self)
        self.gui_runned = False
        self.step()

    def get_dbus_iface(self, app_name):
        try:
            remote_object = self.bus.get_object(DBUS_NAME, app_name)
            return dbus.Interface(remote_object, DBUS_NAME)
        except dbus.DBusException:
            return None

    def ping_app(self, app_name):
        try:
            obj = self.get_dbus_iface(app_name)
            if obj:
                obj.ping()
                return True
        except dbus.DBusException:
            pass
        return False

    def is_console_gui_run(self):
        return self.ping_app(DBUS_MAINAPP)

    def is_gui_update_run(self):
        return self.ping_app(GUI_UPDATE_APP)

    def step_already(self):
        now_gui_runned = self.is_gui_update_run()
        if (self.is_console_gui_run() or
                (not now_gui_runned and
                     (self.update_already_run() or self.gui_runned))):
            self.systray.hide()
        self.gui_runned = now_gui_runned

    def step(self):
        if not self.is_console_gui_run():
            if (self.need_update() and not self.update_already_run() or
                self.is_gui_update_run()):
                self.systray.show()
                return
        self.systray.hide()

if __name__ == '__main__':

    import sys
    if not user_can_run_update():
        sys.stderr.write(_("User can not to perform the system update")+"\n")
        sys.exit(1)

    app = QtGui.QApplication(sys.argv)

    for i in [0.5, 1, 2, 5]:
        if QtGui.QSystemTrayIcon.isSystemTrayAvailable():
            break
        time.sleep(i)
    else:
        QtGui.QMessageBox.critical(None, "Systray",
                    "I couldn't detect any system tray on this system.")
        sys.exit(1)

    # Enable glib main loop support
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    # Get the session bus
    try:
        bus = dbus.SessionBus()
    except dbus.exceptions.DBusException, e:
        sys.exit(1)

    QtGui.QApplication.setQuitOnLastWindowClosed(False)
    # Export the service
    name = dbus.service.BusName(DBUS_NAME_UPDATER, bus)
    # Export the object
    ct = CheckThread(bus)
    DBusChecker(bus, DBUS_APP_UPDATER, ct)

    sys.exit(app.exec_())
