#!/usr/bin/python3

# Komikku -- A manga reader for GNOME
#
# Copyright (C) 2019-2024 Valéry Febvre <vfebvre@easter-eggs.com>
#
# 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/>.

import gettext
import locale
import os
import sys

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

builddir = os.environ.get('MESON_BUILD_ROOT')
if builddir:
    sys.dont_write_bytecode = True
    sys.path.insert(1, os.environ['MESON_SOURCE_ROOT'])
    xdg_data_dir = os.path.join(builddir, '/usr', 'share')
    os.putenv('XDG_DATA_DIRS', '%s:%s' % (xdg_data_dir, os.getenv('XDG_DATA_DIRS', '/usr/local/share/:/usr/share/')))


def install_excepthook():
    """ Make sure we exit when an unhandled exception occurs. """
    old_hook = sys.excepthook

    def new_hook(etype, evalue, etb):
        print('Error: An unhandled exception occurs')

        old_hook(etype, evalue, etb)

        context = GLib.main_context_default()
        done = False
        while context.iteration():
            if done:
                continue
            app = Gio.Application.get_default()
            if app.window:
                app.window.quit(force=True)
            else:
                app.quit()
            done = True

        sys.exit()

    sys.excepthook = new_hook


if __name__ == '__main__':
    import gi

    gi.require_version('Gtk', '4.0')
    gi.require_version('Adw', '1')

    from gi.repository import Gio
    from gi.repository import GLib
    from gi.repository import Gtk

    install_excepthook()

    # Why both locale and gettext are needed?
    # gettext works for the python part but not for XML UI files!
    try:
        locale.textdomain('komikku')
        locale.bindtextdomain('komikku', '/usr/share/locale')
    except AttributeError as e:
        # Python built without gettext support doesn't have bindtextdomain() and textdomain()
        print('Could not bind the gettext translation domain. Some translations will not work.')
        print('Error: {}'.format(e))
    gettext.textdomain('komikku')
    gettext.bindtextdomain('komikku', '/usr/share/locale')

    resource = Gio.Resource.load(os.path.join('/usr/share/komikku', 'info.febvre.Komikku.gresource'))
    resource._register()

    from komikku.application import Application

    Application.application_id = 'info.febvre.Komikku'
    Application.author = 'Valéry Febvre'
    Application.profile = "default"
    Application.version = '1.65.0'
    app = Application()

    try:
        status = app.run(sys.argv)
    except SystemExit as e:
        status = e.code

    sys.exit(status)
