/***************************** 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 "MvQApplication.h"

#include <cstring>
#include <exception>
#include <fstream>
#include <iostream>
#include "fstream_mars_fix.h"

#include <QtGui>
#include <QStyleFactory>
#include <QMainWindow>

#include <MvTemplates.h>

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

MvQApplication::MvQApplication(int& ac, char** av, const char* name, QStringList resources) :
    QApplication(ac, av),
    MvApplication(ac, av, name)
{
    // Create socket notifier for the mars event loop.
    // The dataReceived function will be called everytime
    // there is data available in the socket
    int sockfd = getService()->soc;
    sn_ = new QSocketNotifier(sockfd, QSocketNotifier::Read);
    QObject::connect(sn_, SIGNAL(activated(int)),
                     this, SLOT(slotDataReceived(int)));

    // Get desktop name
    char* desktop = getenv("MV_DESKTOP_NAME");
    if (desktop == nullptr) {
        std::cout << "Error: MV_DESKTOP_NAME is not defined! MvQApplication exits" << std::endl;
        exit(1);
    }

    std::string dn(desktop);
    desktopName_ = new char[dn.size() + 1];
    desktopName_[dn.size()] = '\0';
    std::memcpy(desktopName_, dn.c_str(), dn.size());

    // Get qt style
    char* styleCh = getenv("METVIEW_QT_STYLE");
    if (styleCh == nullptr) {
        marslog(LOG_EROR, " Error: METVIEW_QT_STYLE is not defined! MvQApplication exits");
        exit(1);
    }

    std::string style(styleCh);
    QStringList styleLst = QStyleFactory::keys();
    QString styleQs = QString::fromStdString(style);
    if (styleLst.contains(styleQs)) {
        marslog(LOG_INFO, "Setting qt style to: %s", style.c_str());
        setStyle(styleQs);
    }

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

    //---------------------------
    // Set QSettings location
    //---------------------------

    // Set a custom location inside the metview home directory for qsettings
    if (char* spCh = getenv("METVIEW_USER_DIRECTORY")) {
        std::string sp(spCh);
        sp += "/System/Preferences/._mv_desktop_config_";
        marslog(LOG_INFO, "QSettings path is set to: %s", sp.c_str());
        MvQ::initSettings(QString::fromStdString(sp));
    }

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

    //    // init application logger
    //    MvLog::registerApp(this);
}

MvQApplication::~MvQApplication()
{
    delete[] desktopName_;
}

void MvQApplication::slotDataReceived(int)
{
    // Disable the notifier
    // Process data from the socket
    // Re-enable the notifier if you are interested in more data
    //	const QMetaObject *tt = metaObject ();
    //	sn_->setEnabled(false);

    process_service(getService());

    //	sn_->setEnabled(true);
}

void MvQApplication::processDropRequest(MvRequest* req)
{
    send_drop_info(getService(), desktopName_, *req, 0);
}

// static callback function for message
void MvQApplication::messageCallbackCore(svcid* id, request* r, void* obj)
{
#ifdef MVQSERVICE_DEBUG__
    std::cout << "MvQService::messageCallback" << std::endl;
    print_all_requests(r);
#endif
    if (auto* s = static_cast<MvQApplication*>(obj))
        s->messageCallback(id, r);
}

// the apps own callback function for message
void MvQApplication::messageCallback(svcid* /*id*/, request* r)
{
    if (strcmp(r->name, "RAISE_WINDOW") == 0 && win_) {
        auto pidStr = std::to_string(getpid());
        if (!pidStr.empty() && strcmp(get_value(r, "PID", 0), pidStr.c_str()) == 0) {
#ifdef MVQSERVICE_DEBUG__
            std::cout << "   raise window for PID=" << pidStr << std::endl;
#endif
            win_->showNormal();
            win_->raise();
        }
    }
}

void MvQApplication::registerToDesktop(QMainWindow* win)
{
    if (win == nullptr)
        return;

    win_ = win;
    add_message_callback(MvApplication::getService(), nullptr,
                         messageCallbackCore, (void*)this);
}

void MvQApplication::writePidToFile(const MvRequest& r)
{
    if (const char* ch = r("_PID_FILE")) {
        std::ofstream f;
        f.open(ch);
        if (f.good())
            // marslog(LOG_INFO,"pid written=%d to file=%s", getpid(), ch);
            f << getpid();
        f.close();
    }
}

// Handle uncaught exceptions
bool MvQApplication::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 MvQApplication::writeToUiLog(const std::string& msg, MvLogLevel level, bool popup)
{
    if (popup) {
        MvQ::showMessageBox(msg, level);
    }
}
