#!/usr/bin/env python3

import sys
import os
import locale
import gettext

if 'EOLIE_TRACE' in os.environ:
    from pycallgraph import PyCallGraph
    from pycallgraph.output import GraphvizOutput

# Make sure we'll find the eolie modules, even in JHBuild
sys.path.insert(1, '/usr/lib/python3.11/site-packages/')

from gi.repository import Gio

localedir = '/usr/share/locale'
pkgdatadir = '/usr/share/eolie'

from eolie.application import Application

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

    def new_hook(etype, evalue, etb):
        old_hook(etype, evalue, etb)
        while Gtk.main_level():
            Gtk.main_quit()
        sys.exit()
    sys.excepthook = new_hook

if __name__ == "__main__":
    install_excepthook()
    
    try:
        locale.bindtextdomain('eolie', localedir)
        locale.textdomain('eolie')
    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('eolie', localedir)
    gettext.textdomain('eolie')

    resource = Gio.resource_load(os.path.join(pkgdatadir, 'eolie.gresource'))
    Gio.Resource._register(resource)

    app_id = None if "org.gnome.Eolie" == "None" else "org.gnome.Eolie"
    app = Application("0.9.101", pkgdatadir, app_id)
    if 'EOLIE_TRACE' in os.environ:
        graphviz = GraphvizOutput()
        graphviz.output_file = 'eolie.png'
        with PyCallGraph(output=graphviz):
            exit_status = app.run(sys.argv)
            sys.exit(exit_status)
    else:
        exit_status = app.run(sys.argv)
        sys.exit(exit_status)
