#!/usr/local/bin/python3.13

# the main program. Relies on fract4d libs to do the real work

# python stdlib
import sys
import os

# gettext
import gettext
os.environ.setdefault('LANG', 'en')
if os.path.isdir('po'):
    gettext.install('gnofract4d', 'po')
else:
    gettext.install('gnofract4d')

try:
    # nogui modules
    from fract4d import fractconfig, fractmain
    from fract4d.options import Arguments
except ImportError as err:
    print(_("Can't import a required module."))
    if "fract4dc" in str(err):
        print(_("If you haven't set up Gnofract 4D yet, run:\n"
                "./setup.py build\n"))
    print(_("Error was: '%s'") % err)
    sys.exit(1)

def main(args):
    # saved options
    userConfig = fractconfig.userConfig()

    # command line options
    opts = Arguments().parse_args(args)

    try:
        if opts.nogui:
            plainmain(userConfig, opts)
        else:
            gtkmain(userConfig, opts)
    except Exception as err:
        print("A fatal error occurred:\n\t%s\n\n" % str(err))
        raise

def gtkmain(userConfig, options):
    # GTK+
    import gi
    gi.require_version('Gtk', '3.0')
    try:
        from gi.repository import Gtk
    except ImportError as err:
        print(_("Can't find Gtk. You need to install it before you can run Gnofract 4D."))
        sys.exit(1)

    try:
        # GUI module
        from fract4dgui import main_window
    except ImportError as err:
        print(_("Can't import a required module."))
        print(_("Error was: '%s'") % err)
        sys.exit(1)

    mainWindow = main_window.MainWindow(userConfig)
    mainWindow.apply_options(options)

    if mainWindow.f.thaw():
        gi.require_version('GLib', '2.0')
        from gi.repository import GLib
        GLib.idle_add(mainWindow.on_fractal_change)

    Gtk.main()

def plainmain(userConfig, options):
    t = fractmain.T(userConfig)
    t.run(options)

def main_n(n):
    for i in range(n):
        main(sys.argv[1:])

if __name__ == '__main__':
    if os.environ.get("DO_GF4D_PROFILE"):
        import cProfile
        import pstats
        prof = cProfile.Profile()
        prof.runcall(main_n, 5)
        stats = pstats.Stats(prof)
        stats.sort_stats("cumulative")
        stats.dump_stats("gf4d.prof")
        stats.print_stats()
    else:
        main(sys.argv[1:])
