/***************************** 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 <QtGui>
#include <QStyleFactory>
#include <QMainWindow>

#include <MvTemplates.h>

#include "MvQApplication.h"
#include "MvQMethods.h"
#include "PmContext.h"

MvQApplication::MvQApplication(int& ac, char** av, const char* name) :
    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 == 0) {
        std::cout << "Error: MV_DESKTOP_NAME is not defined! MvQApplication exits" << endl;
        exit(1);
    }

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

    //Get qt style
    char* styleCh = getenv("METVIEW_QT_STYLE");
    if (styleCh == 0) {
        cout << "Error: METVIEW_QT_STYLE is not defined! MvQApplication exits" << endl;
        exit(1);
    }

    QString style(styleCh);

    QStringList styleLst = QStyleFactory::keys();
    if (styleLst.contains(style)) {
        setStyle(style);
    }

    //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")) {
        QString sp(spCh);
        sp += "/System/Preferences/._mv_desktop_config_";
        std::cout << "QSettings path is set to:" << sp.toStdString() << std::endl;
        MvQ::initSettings(sp);
    }
}

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 (MvQApplication* 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(), NULL,
                         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();
    }
}

