/***************************** 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 "uPlotService.hpp"

#include <sys/stat.h>

#include <iostream>
#include <sstream>
#include <string>

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

// 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() = default;

uPlotService::~uPlotService() = default;

// --- 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();
    std::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 == nullptr) {
        out.setVerb("ERROR");
        out("MESSAGE") = "uPlotService-> MV_DESKTOP_NAME is not defined!";
        return;
    }
    std::string desktopName(desktop);
    out("TARGET") = desktopName.c_str();

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

    // Does this request contain a directive to change the working directory?
    std::string cmd;
    const char* cwd = uPlotRequest("_CWD");
    if (cwd) {
        cmd += "cd " + std::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 " + std::string(ftemp) + " $METVIEW_QT_APPLICATION_FLAGS &";
    cmd += "$metview_command $METVIEW_BIN/uPlot " + std::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" << std::endl;
    }

    // Retrieve the reply request
    auto* serviceTask = dynamic_cast<MvServiceTask*>(task);

    MvRequest replyRequest = serviceTask->getReply();

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

// Use system command to start MetZoom. MetZoom 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 MetZoom in the command line argument.
void uPlotService::CallMetZoom(MvRequest& in, MvRequest& out)
{
    std::cout << "MetZoomService::serve in" << std::endl;
    in.print();

    // Set filename to be used by MetZoom to store the output request
    MvRequest req = in;
    // std::string appName = "uPlotManager" + std::to_string(getpid());
    // std::string name = MakeTmpPath(appName.c_str());
    // req("_UPLOT_MANAGER_ID") = (const char*)name.c_str();

    /*
    // Plotting procedure relies on parameter _CLASS being defined
    std::string verb;
    if ( (const char*)req("_CLASS") )
       verb = (const char*)req("_CLASS");
    else
    {
        out.setVerb("ERROR");
        out("MESSAGE") = "MetZoom error: input request not recognised";
        return;
    }
*/
    // Input request: update verb and save it in the METVIEW_TMP directory
    // If in the future we change the verb to MetZoom then we need
    // to uncomment the line below
    // req.setVerb(verb.c_str());

    MvTmpFile reqFile(false);
    // std::string temp = MakeTmpPath("MetZoom.req");
    req.save(reqFile.path().c_str());

    // 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!!!!!!!

    if (const char* ch = getenv("MV_DESKTOP_NAME")) {
        out.setVerb("REPLY");
        out("TARGET") = ch;
    }
    else {
        out.setVerb("ERROR");
        out("MESSAGE") = "MetZoom-> MV_DESKTOP_NAME is not defined!";
        return;
    }

    // Call MetZoom script
    std::string mzStartPath;
    if (const char* ch = getenv("MV_METZOOM_START_CMD")) {
        mzStartPath = std::string(ch);
    }
    // } else {
    // 	out.setVerb("ERROR");
    // 	out("MESSAGE") = "MetZoom error: environmental variable MV_METZOOM_START_CMD not defined";
    // 	return;
    // }

    std::string cmd = "python3 ";
    if (mzStartPath.empty()) {
        cmd = "metzoom_run";
    }
    else {
        cmd = mzStartPath;
    }
    cmd += " --console-log --log=DEBUG --request=" + reqFile.path();
    std::cout << "Calling: " << cmd << std::endl;

    int istatus = system(cmd.c_str());
    if (istatus) {
        char* errmsg = strerror(errno);
        std::ostringstream oss;
        oss << "Error trying to start MetZoom. Error: " << errmsg << ". System command: " << cmd;
        out.setVerb("ERROR");
        out("MESSAGE") = oss.str().c_str();
        return;
    }

    // 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);
    }
    */

    std::cout << "MetZoomService::serve out" << std::endl;
    out.print();

    return;
}
