#!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2015 - Lionel Dricot & Bertrand Rousseau
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
#==============================================================================
#
# Getting things GNOME!: a gtd-inspired organizer for GNOME
#
# @author : B. Rousseau, L. Dricot
# @date   : November 2008
#
#   main.py contains the configuration and data structures loader
#   taskbrowser.py contains the main GTK interface for the tasklist
#   task.py contains the implementation of a task and a project
#   taskeditor contains the GTK interface for task editing
#       (it's the window you see when writing a task)
#   backends/xml_backend.py is the way to store tasks and project in XML
#
#   tid stand for "Task ID"
#   pid stand for "Project ID"
#   uid stand for "Universal ID" which is generally the tuple [pid,tid]
#
#   Each id are *strings*
#   tid are the form "X@Y" where Y is the pid.
#   For example : 21@2 is the 21st task of the 2nd project
#   This way, we are sure that a tid is unique accross multiple projects
#
#==============================================================================

"""This is the top-level exec script for running GTG"""

#=== IMPORT ===================================================================
import sys
import argparse
import gettext
import locale
import signal

if __name__ == "__main__":
    # Set up UI i18n so module-level translations work
    LOCALE_DIR = '/usr/local/share/locale'

    try:
        locale.bindtextdomain('gtg', LOCALE_DIR)
        locale.textdomain('gtg')
    except AttributeError as e:
        # Python built without gettext support doesn't have bindtextdomain() and textdomain()
        print("Couldn't bind the gettext translation domain. Some translations won't work.\n{}".format(e))

    gettext.bindtextdomain('gtg', LOCALE_DIR)
    gettext.textdomain('gtg')

    try:
        import setproctitle
        setproctitle.setproctitle("gtg")
    except ImportError:
        pass

import gi
gi.require_version('Gdk', '3.0')
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '4') 

from gi.repository import GLib

_LOCAL = False

if _LOCAL:
    sys.path.insert(1, '/usr/local/lib/python3.12/site-packages')

from GTG.core import info
from GTG.gtk.application import Application
from GTG.gtk.errorhandler import replace_excepthook


def handle_local_options(application, options):
    """
    Handle local options passed to the application, such as --version, --debug
    and --title.
    This is called by the Application object via the handle_local_options signal
    """
    version = options.lookup_value("version", None)
    if version is not None and version:
        print("GTG (Getting Things GNOME!)", info.VERSION)
        print("Using python", sys.version)
        print("For more information:", info.URL)
        return 0 # Exit successfully

    debug = options.lookup_value("debug", None)
    if debug is not None:
        debug = debug.unpack()
    application.set_logging(bool(debug))

    title = options.lookup_value("title", None)
    if title is not None:
        info.NAME = str(title.unpack())

    return -1 # Continue parsing

if __name__ == "__main__":
    if _LOCAL:
        print("Running from source tree")
    try:
        def N_(message):
            """Mark as to be translated for gettext, don't do any translation here"""
            return message

        application = Application('org.gnome.GTG')

        application.add_main_option(
                "version", ord('v'),
                GLib.OptionFlags.IN_MAIN,
                GLib.OptionArg.NONE,
                # Translators: -v --version cli argument description
                N_("Show program version"),
                None
            )
        application.add_main_option(
                "debug", ord('d'),
                GLib.OptionFlags.NONE,
                GLib.OptionArg.NONE,
                # Translators: -d --debug cli argument description
                N_("Enable debug output"),
                None
            )
        application.add_main_option(
                "title", ord('t'),
                GLib.OptionFlags.NONE,
                GLib.OptionArg.STRING,
                # Translators: -t --title=TITLE cli argument description
                N_("Use special title for windows\' title"),
                # Translators: -t --title=TITLE cli argument placeholder
                N_("TITLE")
            )
        application.connect("handle-local-options", handle_local_options)

        signal.signal(signal.SIGTERM, lambda s, f: application.quit())
        replace_excepthook()
        sys.exit(application.run(sys.argv))

    except KeyboardInterrupt:
        sys.exit(1)
