/***************************** 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 <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QStringList>
#include <QVector>
#include <QXmlFormatter>
#include <QXmlQuery>
#include <QXmlResultItems>

#include "MvQWcsClient.h"
#include "MvQWcsClientEditor.h"
#include "MvQOgcRequest.h"
//#include "MvQOgcServiceManager.h"
#include "Metview.h"
#include "MvQService.h"

using namespace std;

// Globals
int          ac;
char       **av;

class MvWcsClient : public MvQService
{	
   public:
	MvWcsClient() : MvQService("WCSCLIENT") {};
	void serve(MvRequest&,MvRequest&);
	void processUiMode(MvRequest&,MvRequest&);
	void processGetMode(MvRequest&,MvRequest&);
};

void MvWcsClient::serve( MvRequest& in, MvRequest& out)
{
  	cout << "---MvWcsClient::serve() IN---" << endl;
  	in.print();

	// Get user action mode
	const char* mode = (const char*)in("_ACTION");

	if(strcmp(mode,"edit") == 0)
	{
		processUiMode(in,out);
	}
	else if(strcmp(mode,"visualise") == 0 || 
		strcmp(mode,"prepare") ==0 ||
		strcmp(mode,"execute") ==0 )
	{		
		processGetMode(in,out);

	}

	cout << "---MvWcsClient::serve() OUT---" << endl;
	out.print();
}


void MvWcsClient::processUiMode( MvRequest& in, MvRequest& out)
{

	// Get icon filename
	//string filename(getenv("METVIEW_USER_DIRECTORY"));
	//filename += (const char*)in("_NAME");
	string filename((const char*)in("_NAME"));

	//Create the qt application
	QApplication app(ac, av);

	//Initialise resorces from a static library (libMvQtGui)
	Q_INIT_RESOURCE(examiner);
	Q_INIT_RESOURCE(find);
	Q_INIT_RESOURCE(window);

	// Initialize client
	MvQWcsUiClient *wcsClient = new MvQWcsUiClient(filename,in);
	
	
	//QString fconf(mvhome);
	//fconf+="/Metview/Defaults/OgcClient_conf.xml";
 	
	//Create the manager
	//MvQOgcServiceManager *manager=new MvQOgcServiceManager(fconf);

	//Read the icon file and initialize the dialog
	MvQWcsClientEditor *editor=new MvQWcsClientEditor(wcsClient);
	editor->show();
	
	//Listen to the mars event loop!
	setupSocketNotifier();
	
   	//Enter the app loop
 	app.exec();
}

void MvWcsClient::processGetMode( MvRequest& in, MvRequest& out)
{
	QApplication app(ac, av);
	
	MvQWcsGetClient *client = new MvQWcsGetClient(in);
	client->runGetCov();
	
	//Listen to the mars event loop!
	setupSocketNotifier();
	
	//Enter the app loop
 	app.exec();
	
	qDebug() << "App loop exited";

	//If the getMap request failed returns
	if(client->getCovRunStatus() == false)
	{
		setError(13,"GetCoverage request failed!");
		return;
	}

	MvQGetCoverageRequest *gcr = client->getCovRequest();

	MvRequest rdata("NETCDF");
	rdata("PATH") = gcr->outFile().toStdString().c_str();
	rdata("TEMPORARY") = 1;
	rdata.print();
	out = rdata;


	//Else build the output request

	/*MvRequest req("PRASTER");
	req("IMPORT_FILE_TYPE") = "png",
	req("IMPORT_X_POSITION") = -180;
	req("IMPORT_Y_POSITION") = -90;
	req("IMPORT_WIDTH") = 360;
	req("IMPORT_HEIGHT") = 180;
	
	MvQGetMapRequest *gmr = client->getMapRequest();

	req("CRS") = gmr->crs().toStdString().c_str();
	req("CRS_MINX") = gmr->minX().toStdString().c_str();
	req("CRS_MINY") = gmr->minY().toStdString().c_str();
	req("CRS_MAXX") = gmr->maxX().toStdString().c_str();
	req("CRS_MAXY") = gmr->maxY().toStdString().c_str();
	req("LAYERS") = gmr->layers().toStdString().c_str();
	
	req("SERVICE")="WCS";

	const char *description=static_cast<const char*>(in("LAYER_DESCRIPTION"));
	if(description) req("DESCRIPTION") = description;

	const char *title=static_cast<const char*>(in("SERVICE_TITLE"));
	if(title) req("TITLE") = title;

	const char *url=static_cast<const char*>(in("SERVER"));
	if(url) req("URL") = url;

	//Build rasterloop if there is time dimension in the GetMap request
	if(gmr->isTimePresent())
	{
		MvRequest reqLoop;

		QVector<MvRequest> rStep(gmr->requestStepNum());	
		for(unsigned int i=0; i < rStep.count(); i++)
		{
			MvRequest reqStep=req;
			QString fnam=gmr->outFile(i);
			reqStep("IMPORT_FILE_PATH") = fnam.toStdString().c_str();
			reqStep("PATH") = fnam.toStdString().c_str();
			reqStep("TIME") = gmr->time(i).toStdString().c_str();
			reqLoop = reqLoop + reqStep;
		}	

		out.setVerb("PRASTERLOOP");
		out("RASTERS") = reqLoop;
	}
	else
	{
		MvRequest reqStep=req;
		QString fnam=gmr->outFile(0);
		reqStep("IMPORT_FILE_PATH") = fnam.toStdString().c_str();
		reqStep("PATH")       = fnam.toStdString().c_str();

		out.setVerb("PRASTERLOOP");
		out("RASTERS") = reqStep;	
	}

	out("IMPORT_X_POSITION") = -180;
	out("IMPORT_Y_POSITION") = -90;
	out("IMPORT_WIDTH") = 360;
	out("IMPORT_HEIGHT") = 180;*/

}


int main( int argc, char **argv)
{
	ac = argc;
  	av = argv;

	// Initialize a Metview application
	MvApplication app(argc,argv,"wcsclient");

	// Instantiate the application
	MvWcsClient ogc;
	//ogc.saveToPool(false);
	app.run();
}
