from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QMessageBox, QWidget, QStyleFactory
from PyQt6 import QtGui
import sys

from mvp.view import MainWindow
from mvp.model import OptimizationModel, SettingsModel, FlyModel
from mvp.presenter import MainPresenter

from logger import logger


def balloon_app():
    if QApplication.instance():
        _app = QApplication.instance()
    else:
        _app = QApplication(sys.argv)
    return _app


if __name__ == "__main__":
    app = balloon_app()
    app.setStyle(QStyleFactory.create("Fusion"))
    logger.info("Application started")
    try:
        # Initialize Models
        settings_model = SettingsModel()
        optimization_model = OptimizationModel(settings_model)
        fly_model = FlyModel(optimization_model, settings_model)

        # Initialize Main View - Main Window
        main_window = MainWindow()

        # Initialize Main Presenter and pass Models and View
        main_presenter = MainPresenter(
            main_window, optimization_model, fly_model, settings_model
        )

        # Show main window
        main_window.show()
        main_window.showMaximized()
        sys_exit_status = app.exec()
    except RuntimeError as error:
        ex = QWidget()
        QMessageBox.warning(ex, "Error", str(error))
        logger.error("Runtime Error: %s", str(error))
    else:
        logger.info("Application closed")
        sys.exit(sys_exit_status)
