#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Author: Milan Nikolic <gen2brain@gmail.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 os
import sys
import platform
import signal
import traceback

if os.path.isdir(os.path.join("..", "src")) and os.path.isfile(
        os.path.join("..", "setup.py")):
    sys.path.insert(0, os.path.realpath(os.path.join("..", "src")))

os.environ["DBUS_FATAL_WARNINGS"] = "0"

try:
    from PyQt6.QtWidgets import QApplication
    from PyQt6.QtCore import Qt, QLocale, QTranslator
except ImportError as err:
    sys.stderr.write("This application needs PyQt6 module%sError:%s%s" % (
        os.linesep, str(err), os.linesep))
    sys.exit(1)

try:
    from m64py.core.defs import FRONTEND_VERSION
except ImportError as err:
    sys.stderr.write("Can't import m64py modules%sError:%s%s" % (
        os.linesep, str(err), os.linesep))
    sys.exit(1)

try:
    from m64py.ui import i18n_rc
except ImportError:
    sys.stderr.write("You have to run setup.py build first\n")
    sys.exit(1)

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        return
    print("".join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    sys.exit(1)

sys.excepthook = handle_exception

if __name__ == "__main__":
    app = QApplication(sys.argv)
    from m64py.opts import opts, args

    app.setDesktopFileName("net.sourceforge.m64py.M64Py")

    locale = QLocale.system().name()
    translator = QTranslator()
    if translator.load(":i18n/m64py_" + locale, ":/"):
        app.installTranslator(translator)

    sys.stderr.write("M64Py version %s (%s %s/%s)\n\n" % (
        FRONTEND_VERSION, platform.system(), platform.release(), app.platformName().title()))

    from m64py.frontend.mainwindow import MainWindow
    window = MainWindow((opts, args))
    window.show()
    window.raise_()

    try:
        try:
            signal.siginterrupt(signal.SIGCHLD, False)
            signal.signal(signal.SIGINT, signal.SIG_DFL)
        except AttributeError:
            pass
        sys.exit(app.exec())
    except KeyboardInterrupt:
        pass
