#!/usr/bin/python3

import gettext
from gi.repository import Gio, GLib

import locale
import os
import sys

from iotas import const


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

    def new_hook(etype, evalue, etb):
        old_hook(etype, evalue, etb)
        app = Gio.Application.get_default()
        if app is not None:
            app.quit()

        sys.exit()

    sys.excepthook = new_hook


def main():
    install_excepthook()
    try:
        locale.bindtextdomain(const.GETTEXT_PACKAGE, const.LOCALEDIR)
        locale.textdomain(const.GETTEXT_PACKAGE)
    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(const.GETTEXT_PACKAGE, const.LOCALEDIR)
    gettext.textdomain(const.GETTEXT_PACKAGE)

    resource = Gio.resource_load(os.path.join(const.PKGDATADIR, "resources.gresource"))
    Gio.resources_register(resource)

    GLib.set_application_name("Iotas" + const.SUFFIX)

    from iotas.application import Application

    app = Application()

    exit_status = app.run(sys.argv)
    sys.exit(exit_status)


if __name__ == "__main__":
    main()
