#!/usr/bin/env python3

# 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"
                "  meson setup _build\n"
                "  meson compile -C _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):
    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)

    app = main_window.Application(options, userConfig)
    app.run()

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:])
