/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQSimpleApplication.h"

#include <exception>

#include <QStyleFactory>
#include <QFont>

#include "MvQMethods.h"
#include "MvQTheme.h"
#include "MvException.h"
#include "MvLog.h"

MvQSimpleApplication::MvQSimpleApplication(int& ac, char** av, const char* name, QStringList resources) :
    QApplication(ac, av),
    MvAbstractApplication(name)
{
    //Init the style
    QStringList styleLst = QStyleFactory::keys();

    //Set the style
    QString style = "Plastique";
    if (styleLst.contains(style)) {
        setStyle(style);
    }
    else {
        style = "Fusion";
        if (styleLst.contains(style)) {
            setStyle(style);
        }
    }

    //Set fontsize if defined in env var
    if (const char* fontSizeCh = getenv("CODES_UI_FONT_SIZE")) {
        int fontSize = atoi(fontSizeCh);
        if (fontSize < 8)
            fontSize = 8;
        else if (fontSize > 28)
            fontSize = 28;
        QFont f = font();
        f.setPointSize(fontSize);
        setFont(f);
    }

    // load ui theme
    MvQTheme::init(this, resources);
}

// Handle uncaught exceptions
bool MvQSimpleApplication::notify(QObject* receiver, QEvent* event)
{
    static std::string txtIntro{"Fatal error: " + name() + " raised an uncaught exception!\n\nError: "};

    try {
        return QApplication::notify(receiver, event);
    }
    catch (const MvException& e) {
        std::string txt = txtIntro + std::string((e.what()) ? e.what() : "");
        abortWithPopup(txt);
    }
    catch (const std::exception& e) {
        std::string txt = txtIntro + std::string((e.what()) ? e.what() : "");
        abortWithPopup(txt);
    }
    return false;
}

void MvQSimpleApplication::writeToLog(const std::string& /*msg*/, MvLogLevel /*level*/)
{
}

void MvQSimpleApplication::writeToUiLog(const std::string& /*msg*/, MvLogLevel /*level*/, bool /*popup*/)
{
}

void MvQSimpleApplication::exitWithError()
{
}
