#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Unity Mail, QuickList URL processor
# Authors: Dmitry Shachnev <mitya57@gmail.com>
#          Robert Tari <robert.tari@gmail.com>
# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html

import sys
import subprocess
import dbus
from gi.repository import GLib
from dbus.mainloop.glib import DBusGMainLoop
from UnityMail import isRunning, openURLOrCommand, printNames

if __name__ == '__main__':

    if len(sys.argv) > 1:

        if isRunning() and sys.argv[1] == 'Home':

            bInit = False

            DBusGMainLoop(set_as_default=True)
            oSessionBus = dbus.SessionBus()

            try:

                oSession = oSessionBus.get_object('in.tari.unitymail', '/in/tari/unitymail')
                oInterface = dbus.Interface(oSession, 'in.tari.unitymail')
                oLoop = GLib.MainLoop()

                def replyHandler(b):

                    global bInit
                    bInit = b
                    oLoop.quit()

                oInterface.isinit(reply_handler=replyHandler, error_handler=lambda o: oLoop.quit())
                oLoop.run()

                if not bInit:

                    oInterface.settings(reply_handler=lambda: oLoop.quit(), error_handler=lambda o: oLoop.quit())

                    oLoop = GLib.MainLoop()
                    oLoop.run()

                    sys.exit(0)

            except dbus.DBusException as oDBusException:

                print(oDBusException)
                sys.exit(1)

        elif not isRunning() and sys.argv[1] == 'Home':

            subprocess.Popen(['unity-mail'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            sys.exit(0)

        openURLOrCommand(sys.argv[1])

    else:

        print('Error: please specify the URL name.')
        printNames()
        sys.exit(1)

    sys.exit(0)

