/***************************** 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 "uPlot.h"
#include "MvRequest.h"
#include "Root.h"
#include "MvDebugPrintControl.h"
#include "PlotModInteractive.h"
#include "uPlotApp.h"
#include "MagPlusInteractiveService.h"
#include "SuperPage.h"
#include <mars.h>

using namespace std;

bool SetUplotEnv (int argc, char **argv, MvRequest &req, bool &reqExists)
{
	// Create Root instance
	Root::Create();

	// Initialize Mars communication
	marsinit(&argc,argv,0,0,0);
	mvSetMarslogLevel();

	// Read the input request, if available
	reqExists = false;
	if (argc > 1)
	{
		//Check if the input request exists
		if ( access(argv[1],F_OK) == 0 )
		{
			//Read the initial input request saved by uPlotManager
			req.read(argv[1]);
			req.print();

			// Skip UPLOT_MANAGER request
			if ( strcmp(req.getVerb(),"UPLOT_MANAGER") == 0)
				req.advance();

			reqExists = true;
		}
	}

//DOES IT NEED TO TEST FOR INTERACTIVE MODE?????
// CHECK THIS CODE LATER WHEN THE EXPORT BUTTON IS ACTIVATED
#if 0
	// Batch or Interactive mode
	const char *metviewMode = getenv("METVIEW_MODE");
	if ( metviewMode && strcmp(metviewMode,"batch") == 0 )
	{
		// Initialize uPlot in batch mode
		PlotMod::Instance().SetBatchMode();
	}
	else
	{
		// Initialize uPlot in interactive mode
		PlotMod::Instance().SetInteractiveMode();

		// Indicate if a window needs to be created
		bool dispWindow = true;
		if (reqExists)
		{
			// Check if a Display Window needs to be created
			MvRequest reqaux = req.justOneRequest();
			dispWindow = PlotMod::Instance().CheckSetWindowOutputFormat(reqaux);
		}
		PlotMod::Instance().SetWindowMode(dispWindow);
	}

	return PlotMod::Instance().IsWindow();
#endif
	return true;
}

string GetProcessName ()
{
	// Build a process name according to the process id
	char name[64];
	sprintf(name,"uPlot%ld",(long int)getpid());

	return string(name);
}

int main(int argc, char **argv)
{
	// Get process name
	string name = GetProcessName();

	MvRequest req;
	bool reqExists;

	// Setup uPlot environment
	if ( SetUplotEnv(argc,argv,req,reqExists) )
	{
		//Initialise resorces from a static library (libMvQtGui)
		Q_INIT_RESOURCE(window);
		Q_INIT_RESOURCE(keyDialog);

		// Start uPlot interactively with Qt facilities
		uPlotApp app(argc, argv, name.c_str());
		MagPlusInteractiveService* magplus = new MagPlusInteractiveService();
		MagPlusService::Instance(magplus);
				
		PlotModInteractive* pm = new PlotModInteractive();
		PlotMod::Instance(pm);

		// Instantiate uPlot Display Window
		uPlotBase *pw = new uPlot;
		magplus->setPlotApplication(pw);
		SuperPage::setPlotApplication(pw);		
		pm->setPlotApplication(pw);
		
		//PlotModInteractive* pm = new PlotModInteractive();
		//PlotMod::Instance(pm);

		// Instantiate uPlot Display Window
		//uPlot *pw = new uPlot;

		// Initialize plotting dimension
		double x = 29.7;
		double y = 21.;
		pw->setPlotWidgetSize(x,y);

		// Enable Drag and Drop
		pw->EnableDropAction(name);

		// Call myself to execute the initial request
		// It needs to be execute after uPlot window has been created
		if(reqExists)
			MvApplication::callService ( name.c_str(),req,0 );

		// Show uPlot
		pw->show();
		
		return app.exec();
	}

//DOES IT NEED TO TEST FOR INTERACTIVE MODE?????
// CHECK THIS CODE LATER WHEN THE EXPORT BUTTON IS ACTIVATED

	else
	{
		// Start uPlot without a window (eg. batch mode or interactive mode
		// without a Qt window)
//		uPlotApp app(argc, argv, name.c_str());

		// Call myself to execute the initial request
//		if(reqExists)
//			MvApplication::callService ( name.c_str(),req,0 );

//		app.run();
	}

 	Root::ServerDead(0,0);
}
