/***************************** 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 "DataToolManager.h"
#include "MvServiceTask.h"

int main(int argc, char** argv)
{
    // Set option -debug to true
    // This is needed in order to force the Save Request command
    // to save the hidden parameters too (underscore parameters).
    option opts[] = {"debug", "MARS_DEBUG", "-debug", "1", t_boolean,
                     sizeof(boolean), OFFSET(globals, debug)};

    MvApplication theApp(argc, argv, nullptr, &mars, 1, opts);

    //	DataToolManager vis1("GRIB");
    DataToolManager vis1("ODB_DB");
    //	DataToolManager vis2("GEOPOINTS");
    //	DataToolManager vis3("NETCDF");

    // The applications don't try to read or write from pool, this
    // should not be done with the new PlotMod.
    vis1.saveToPool(false);

    theApp.run();
}

//-------------------------------------------------------------

DataToolManager::DataToolManager(const char* kw) :
    MvService(kw)
{
    // empty
}

void DataToolManager::serve(MvRequest& in, MvRequest& out)
{
    std::cout << "DataToolManager::serve in" << std::endl;
    in.print();

    // Call function to process the request
    DataToolService::Instance().CallDataTool(in, out);

    std::cout << "DataToolManager::serve out" << std::endl;
    out.print();
    return;
}

//--------------------------------------------------------

// Methods for the DataToolService class
//

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

DataToolService&
DataToolService::Instance()
{
    static DataToolService dataToolServiceInstance_;
    return dataToolServiceInstance_;
}

DataToolService::DataToolService()
{
    // Empty
}

DataToolService::~DataToolService()
{
    // Empty
}

// --- METHOD:  CallDataTool
//
// --- PURPOSE: Calls DataTool
//
// --- INPUT:   (a) Request containing an action for DataTool to process
void DataToolService::CallDataTool(MvRequest& in, MvRequest& out)
{
    // Use system command to start the appropriate DataTool service.
    // The service 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 the service in the command line argument.

    // Save request to be processed by the appropriate service
    const char* ftemp = marstmp();
    in.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");
    out("TARGET") = "MetviewUI";  //????????????

    // Start the approriate service
    char cmd[1024];
    /*if ( strcmp(in.getVerb(),"GRIB") == 0 )
    {
        sprintf(cmd,"$metview_command $METVIEW_BIN/GribTool %s -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss&",ftemp);
    }*/

#ifdef METVIEW_EXPERIMENTAL

    if (strcmp(in.getVerb(), "ODB_DB") == 0) {
        sprintf(cmd, "$metview_command $METVIEW_BIN/OdbToolBox %s $METVIEW_QT_APPLICATION_FLAGS &", ftemp);
    }

    system(cmd);
#endif
}

void DataToolService::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++ ) )

        //		PlotMod::MetviewError ( "uPlot crashed" );
        //		COUT << "DataTool crashed" << std::endl;
    }

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

    MvRequest replyRequest = serviceTask->getReply();
    replyRequest.print();

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