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

	// 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)  
	{	
		cout << "Error: MV_DESKTOP_NAME is not defined! GeoTool exits!" << endl;
		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);
	}

	string cmd;

	// does this request contain a directive to change the working directory?
	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+="$metview_command $METVIEW_BIN/uPlot " + string(ftemp) + " $METVIEW_QT_APPLICATION_FLAGS &";
		
	system(cmd.c_str());
#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 )
{
cout << " END OF CALLUPLOT " << endl;
	// 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 << "uPlot crashed" << 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 );
}
