#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# Authors: Quinn Storm (livinglatexkali@gmail.com)
#          Patrick Niklaus (patrick.niklaus@student.kit.edu)
# Copyright (C) 2007 Quinn Storm

import gi
gi.require_version('Pango', '1.0')
gi.require_version('PangoCairo', '1.0')
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
from gi.repository import GLib, Gio, Gtk, Gdk
import os
import sys
import signal
import compizconfig
import ccm
from ccm.Utils import GlobalUpdater
from ccm.Constants import Version
from ccm.Utils import GLIB_VERSION, GTK_VERSION
if GLIB_VERSION < (2, 42, 0):
    import optparse

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

def command_line(application, cmdLine, context):
    options  = {"plugin": None, "category": None, "version": False}
    plugin   = None
    category = None

    if GLIB_VERSION >= (2, 42, 0):
        optionValues = cmdLine.get_options_dict()
        for option in options.keys():
            if optionValues.contains(option):
                options.update({option:
                                optionValues.lookup_value(option).unpack()})
    else:
        parser = optparse.OptionParser()
        parser.add_option("-p", "--plugin", dest = "plugin",
                          help = "Directly jump to the page of PLUGIN",
                          metavar = "PLUGIN")
        parser.add_option("-c", "--category", dest = "category",
                          help = "Directly jump to CATEGORY",
                          metavar = "CATEGORY")
        parser.add_option("-v", "--version", dest = "version",
                          action = "store_true", help = "Version")
        (optionValues, _) = parser.parse_args(cmdLine.get_arguments())
        for option in options.keys():
            options.update({option: getattr(optionValues, option)})

    if options["version"]:
        print("CCSM %s" % Version)
        return 0

    if GTK_VERSION >= (3, 6, 0):
        prevWin = application.get_active_window()
    else:
        prevWin = None
        if hasattr(application, "activeWindow"):
            prevWin = application.activeWindow

    if prevWin:
        prevWin.present()
        return 0

    if options["plugin"]:
        plugin = options["plugin"]
    if options["category"]:
        category = options["category"]

    mainWin = ccm.MainWin(context, plugin, category)
    if GTK_VERSION >= (3, 6, 0):
        application.add_window(mainWin)
    else:
        application.activeWindow = mainWin
        mainWin.Application = application
        application.hold()
    idle = ccm.IdleSettingsParser(context, mainWin)
    mainWin.show_all()
    return 0

# Compiz 0.9.x and Compiz 0.8.x compatibility.
try:
    context = compizconfig.Context(ccm.GetDefaultScreenNum())
except (AttributeError, TypeError):
    context = compizconfig.Context(ccm.GetScreenNums())
GlobalUpdater.SetContext(context)

if GTK_VERSION >= (3, 6, 0):
    application = Gtk.Application(application_id="org.compiz.ccsm",
                                  flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
else:
    application = Gio.Application(application_id="org.compiz.ccsm",
                                  flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
application.connect("command-line", command_line, context)

try:
    application.register()
except TypeError:
    application.register(None)

if GLIB_VERSION >= (2, 42, 0):
    application.add_main_option("plugin", b"p", GLib.OptionFlags.NONE,
                                GLib.OptionArg.STRING,
                                "Directly jump to the page of PLUGIN",
                                "PLUGIN")
    application.add_main_option("category", b"c", GLib.OptionFlags.NONE,
                                GLib.OptionArg.STRING,
                                "Directly jump to CATEGORY", "CATEGORY")
    application.add_main_option("version", b"v", GLib.OptionFlags.NONE,
                                GLib.OptionArg.NONE, "Version", None)

if application.get_is_remote():
    sys.stderr.write("Another CCSM instance is already running...\n")
    Gdk.notify_startup_complete()
application.run(sys.argv)
