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

from __future__ import print_function
import sys, os, pwd
from calculate.consolegui import qt
from importlib import reload
from calculate.consolegui.application.more import getRunProc, owner, _print
# import __builtin__
import builtins as __builtin__
import dbus
import dbus.mainloop.glib
reload(sys)
# always utf-8 in py3
# sys.setdefaultencoding("utf-8")
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('console_gui',sys.modules[__name__])

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)


def main():
    from calculate.consolegui.application.ConnectionTabs import (ToolTabWidget,
        parse, SelectedMethodWgt)
    from calculate.consolegui.application.dbus_service import (DBUS_MAINAPP,
        DBUS_NAME, DBUS_METHOD_APP, DBusWidget, dbus_updater_hide_tray)
    __builtin__.__dict__['_print'] = _print
    host, port, args = None, None, None
    parser = parse()
    args = parser.parse_args()
    if args.help:
        parser.print_help()
        sys.exit(0)
    sym_link = os.path.basename(sys.argv[0])
    if sym_link != 'cl-console-gui' and sym_link.startswith("cl-console-gui-"):
        args.method = sym_link[len("cl-console-gui-"):].replace("-","_")
    if args.method:
        app = qt.QApplication(sys.argv)
        app.setQuitOnLastWindowClosed(True)

        ex = SelectedMethodWgt(app, args)
        if args.method == 'update':
            dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
            session_bus = dbus.SessionBus()
            # Export the service
            name = dbus.service.BusName(DBUS_NAME, session_bus)
            # Export the object
            widget = DBusWidget(session_bus, DBUS_METHOD_APP % args.method,
                                ex)
        sys.exit(app.exec_())
    if args.host:
        host = args.host
    if args.port:
        port = args.port

    # 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 as e:
        bus = None
        if not os.getuid():
            _print (_('The user must not be root'))
        else:
            print(e)
        sys.exit(1)

    iface = None
    try:
        # Get the remote object
        remote_object = bus.get_object(DBUS_NAME, DBUS_MAINAPP)
        # Get the remote interface for the remote object
        iface = dbus.Interface(remote_object, DBUS_NAME)
    except dbus.DBusException:
        pass

    app = qt.QApplication(sys.argv)
    app.setApplicationName(_("Calculate Console"))

    second = False
    for run_commands in filter(lambda x:'cl-console-gui' in x[0],getRunProc()):
        if 'python' in run_commands[0]:
            if not '--method' in run_commands[0] and pwd.getpwuid(os.getuid())\
                                            .pw_name == owner(run_commands[1]):
                if second:
                    print('Client already running')
                    if iface:
                        # Call some methods of the remote interface
                        iface.show()
                    sys.exit(0)
                else:
                    second = True

    # Do not complete the program then last window is closed
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    session_bus = dbus.SessionBus()

    app.setQuitOnLastWindowClosed(False)

    ex = ToolTabWidget(app, args = args, host = host, port = port)

    # Export the service
    name = dbus.service.BusName(DBUS_NAME, session_bus)
    # Export the object
    widget = DBusWidget(session_bus, DBUS_MAINAPP, ex)
    sys.exit(app.exec_())

if __name__=='__main__':
    main()
