//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      App/main.cpp
//! @brief     Main function of the whole GUI
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "App/AppOptions.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/Model/Util/Path.h"
#include "GUI/View/Base/Stylesheet.h"
#include "GUI/View/Main/MainWindow.h"
#include "GUI/View/Widget/AppConfig.h"
#include "config_build.h"
#include <QApplication>
#include <QDir>
#include <QIcon>
#include <QLocale>
#include <QMessageBox>
#include <QMetaType>
#include <QtGlobal>
#include <iostream>

void custom_terminate_handler()
{
    try {
        std::rethrow_exception(std::current_exception());
    } catch (const std::exception& ex) {
        std::cerr << "terminate called after throwing a std exception'\n"
                  << "what():" << std::endl;
        std::cerr << ex.what() << std::endl;

        int argc;
        char* argv[1];
        QApplication app(argc, argv); // needed to run QMessageBox
        QMessageBox msgbox(QMessageBox::Critical, "BornAgain: fatal bug",
                           QString("Sorry, you encountered a fatal bug.\n"
                                   "The application will terminate.\n"
                                   "Please note the following and inform the maintainers.\n\n")
                               + ex.what() + "\n",
                           QMessageBox::Ok, nullptr);
        msgbox.exec();
    }
}

int main(int argc, char* argv[])
{
    std::set_terminate(custom_terminate_handler);

    ApplicationOptions options(argc, argv);

    QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
    qRegisterMetaType<QVector<double>>("QVector<double>");

    int ret = -1;
    QApplication app(argc, argv);
    app.setApplicationName("BornAgain");
    app.setApplicationVersion(GUI::Path::getBornAgainVersionString());
    app.setOrganizationName("BornAgain");
#ifndef Q_OS_MAC
    app.setWindowIcon(QIcon(":/images/BornAgain.ico"));
#endif
    GUI::Style::setInitialStyle();

    gApp = std::make_unique<AppConfig>();
    gDoc = std::make_unique<ProjectDocument>();

    MainWindow win;
    gApp->mainWindow = &win;

    if (options.find("geometry"))
        win.resize(options.mainWindowSize());
    if (options.find("project-file"))
        win.loadProject(options.projectFile());
    win.show();

    ret = app.exec();
    return ret;
}
