/***************************** 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 <inc_iostream.h>
#include <sys/stat.h>

#include "Assertions.hpp"
#include "MvPath.hpp"
#include "MvServiceTask.h"
#include "uPlotService.hpp"

// Methods for the uPlot Service class
//

// --- METHOD:  Instance
//
// --- PURPOSE: Provide access to the singleton
//              uPlotService class

uPlotService&
uPlotService::Instance()
{
    static uPlotService uPlotServiceInstance_;
    return uPlotServiceInstance_;
}

uPlotService::uPlotService()
{
    // Empty
}

uPlotService::~uPlotService()
{
}

// --- METHOD:  CalluPlot
//
// --- PURPOSE: Calls uPlot
//
// --- INPUT:   (a) Request containing an action for uPlot to process
void uPlotService::CalluPlot(MvRequest& uPlotRequest, MvRequest& out)
{
#if 1
    // Option 1: Use system command to start uPlot. uPlot will fork,
    // register itself and read the initial request to be processed.
    // This request is stored in a temporary file whose filename is
    // passed to uPlot in the command line argument.

    // Set filename to be used by uPlot to store the output request
    std::ostringstream appName;
    appName << "uPlotManager" << (long int)getpid();
    string name                       = MakeTmpPath(appName.str().c_str());
    uPlotRequest("_UPLOT_MANAGER_ID") = (const char*)name.c_str();

    // Save request to be processed by uPlot
    const char* ftemp = marstmp();
    uPlotRequest.save(ftemp);

    // Tell the caller that the request was done
    // The problem here is that the icon will be green even if uPlot
    // can not process the request.
    // WE NEED TO FIND A BETTER SOLUTION!!!!!!!
    out.setVerb("REPLY");

    char* desktop = getenv("MV_DESKTOP_NAME");
    if (desktop == 0) {
        out.setVerb("ERROR");
        out("MESSAGE") = "uPlotService-> MV_DESKTOP_NAME is not defined!";
        return;
    }
    string desktopName(desktop);
    out("TARGET") = desktopName.c_str();

    string GRIB_DEFINITION_PATH_ENV;
    const char* grb_def_path = getenv("GRIB_DEFINITION_PATH");
    if (grb_def_path) {
        GRIB_DEFINITION_PATH_ENV = string(grb_def_path);
    }

    // Does this request contain a directive to change the working directory?
    string cmd;
    const char* cwd = uPlotRequest("_CWD");
    if (cwd) {
        cmd += "cd " + string(cwd) + ";";
        uPlotRequest.unsetParam("_CWD");
    }

    // Start uPlot
    if (!GRIB_DEFINITION_PATH_ENV.empty()) {
        cmd += "export GRIB_DEFINITION_PATH=" + GRIB_DEFINITION_PATH_ENV + ";";
    }
    //cmd+="xterm -iconic -e /usr/local/apps/totalview/tv8.14.0-16/bin/tv8 $METVIEW_BIN/uPlot -a " + string(ftemp) + " $METVIEW_QT_APPLICATION_FLAGS &";
    cmd += "$metview_command $METVIEW_BIN/uPlot " + string(ftemp) + " $METVIEW_QT_APPLICATION_FLAGS &";

    system(cmd.c_str());

    // FAMI20181119
    // This is a optional code. It can be removed if there is no need to
    // inform the caller if uPlot visualised the request successfuly.
    // Because uPlot is called via a system command, instead of a Metview
    // service, uPlotManager does not know if uPlot visualise the request
    // correctly. The code below waits for the uPlot output request for a
    // limited period of time. It reads the request and sends it to whoever
    // called uPlotManager, for example Desktop. In this case, Desktop will
    // know if the icon needs to be turned green or red.
    int wait_time = 1;
    int ntimes    = 10;
    for (int i = 0; i < ntimes; i++) {
        struct stat buffer;
        if (stat(name.c_str(), &buffer) == 0) {
            out.read(name.c_str());
            remove(name.c_str());
            break;
        }
        sleep(wait_time);
    }
#else
    MvRequest req("DYNSERVICE");
    req("name")     = "uPlot";
    req("fullname") = "Display Module";
    long pid        = getpid();
    req("id")       = pid;
    req("cmd")      = "env LD_LIBRARY_PATH=$MAGPLUS_HOME/lib:$LD_LIBRARY_PATH $metview_command $METVIEW_BIN/uPlot  -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss -graphicssystem raster";

    req = req + uPlotRequest;

    // Call event to process the request
    char buf[64];
    sprintf(buf, "uPlot", pid);
    // Call uPlot to process the request
    //	( new MvServiceTask (this,"uPlot",req) )->run();
    uPlotRequest.advance();
    (new MvServiceTask(this, "uPlot", uPlotRequest))->run();
#endif
}
void uPlotService::endOfTask(MvTask* task)
{
    // If error, send a message and return
    if (task->getError() != 0) {
        //int i = 0;
        //const char* msg = 0;
        //while ( msg = task->getMessage (i++ ) )

        //COUT << "uPlot endOfTask-> Failed to run uPlotService" << endl;
    }

    // Retrieve the reply request
    MvServiceTask* serviceTask = (MvServiceTask*)task;

    MvRequest replyRequest = serviceTask->getReply();

    // Execute the callback procedure
    // Call uPlot
    //	MvApplication::callService ( "uPlot", replyRequest, 0 );
}
