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

#include <QApplication>
#include <QDebug>

#include "MvQFileDialog.h"

#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <unistd.h>
#include "mars.h"

static int    gac;
static char** gav;
static svc*   gs = NULL;

static svcid        *s_id = NULL;
static const char   *path = NULL;
static const char   *iconName  = NULL;
static char         *cptr = NULL;

void cleanup(const char* file);
void save(svcid* id,request* r,void* );

//================================
// MvQSavePool
//================================

MvQSavePool::MvQSavePool(QString iconDir)
{
	fDialog_ = new MvQFileDialog(iconDir,tr("Save as"));
	fDialog_->setAcceptMode(QFileDialog::AcceptSave);

	connect(fDialog_,SIGNAL(accepted()),
		this,SLOT(slotAccept()));

	fDialog_->show();
}

MvQSavePool::~MvQSavePool()
{
  	delete fDialog_;
}

void MvQSavePool::slotAccept()
{
  	QStringList lst=fDialog_->selectedFiles();
  	if(lst.count() > 0)
	{
	  	selectedFile_=lst[0];
	}

	//We leave the event loop
	QApplication::quit();
}

void MvQSavePool::slotCancel()
{
  	//We leave the event loop
	QApplication::quit();
}

//=======================================================
// Main part, reused from the original Xt-based version
//=======================================================

void cleanup(const char* file)
{
  	if(s_id)
    	{
      		if(file)
		{
	  		err err_code = 0;
	  		if( cptr && strcmp( cptr, "GRIB" ) == 0 )
	    		{
	      			request *r = empty_request("WRITE");
	      			set_value(r,"TARGET",  "%s",file);
	      			set_value( r, "FIELDSET", "%s", iconName);
	      			err_code = handle_write(r,NULL);
	      			free_all_requests(r);
	    		}
	  		else
	    		{
	      			err_code = mars_copyfile( path, file );
	    		}

			set_svc_msg( s_id, "Data from %s saved as %s",iconName, file);
		}
     		else
		{
	  		set_svc_msg( s_id, "Data from %s not saved", iconName );
		}

      		send_reply( s_id, NULL );

      		s_id  = NULL;
      		path = NULL;
      		iconName = NULL;
    	}
}

void save(svcid* id,request* r,void* )
{
	if( fork_service(id) > 0 )
    		return;

  	s_id = id;

  	const char *verb=request_verb(r);
  	if( ! verb )
    	{
      		set_svc_err(id, 1);
      		set_svc_msg(id, "This data cannot be saved");
      		return;
    	}

  	printf("verb=%s\n",verb);

  	char *pathStr;

  	if(strcmp(verb,"ODB_GEO_POINTS") == 0 || strcmp(verb,"ODB_GEO_VECTORS") == 0 ||
     	   strcmp(verb,"ODB_XY_POINTS") == 0  || strcmp(verb,"ODB_XY_VECTORS") == 0 ||
           strcmp(verb,"ODB_XY_BINNING") == 0 )
  	{
		pathStr = (char *)get_value( r, "ODB_FILENAME",  0 );
   	}
  	else
  	{
  		pathStr = (char*) get_value( r, "PATH",  0 );
  		/*iconName  = get_value( r, "_NAME", 0 );
  		cptr = r->name;*/
  	}

  	iconName  = get_value( r, "_NAME", 0 );
  	cptr = r->name;

	printf("icon_name=%s\n",iconName);

  	path=pathStr;

  	if(!pathStr )
    	{
      		printf("no path\n");
      		set_svc_err(id, 1);
      		set_svc_msg(id, "This data cannot be saved");
      		return;
    	}

  	if( strcmp( cptr, "GRIB" ) == 0 )
    	{
      		new_variable( iconName, request_to_fieldset(r), 0 );
    	}
   	if( strcmp( cptr, "PRASTER" ) == 0 )
    	{
        	cptr = (char*) get_value( r, "IMPORT_FILE_TYPE",  0 );
    	}

  	const char* senderAppl = (char*) get_value(r,"_APPL", 0);

	//Find out start directory
	string iconDir;
	char *mvDir=getenv("METVIEW_USER_DIRECTORY");
  	const char* buf=mdirname(iconName);

	if(mvDir && buf)
	{
		iconDir=string(mvDir) + "/" + string(buf);
		struct stat iconDirStat;
  		if(! (stat(iconDir.c_str(),&iconDirStat) >=0 && iconDirStat.st_mode & S_IFDIR))
		{
		  	iconDir=string();
		}
	}
	if(mvDir && iconDir.empty())
	{
		iconDir=string(mvDir);
	}

	//Create the qt application
	QApplication app(gac, gav);

	MvQSavePool *qSavepool=new MvQSavePool(QString::fromStdString(iconDir));

 	//Enter the qt app loop
 	app.exec();

	//Now we have left the qt event loop
	QString fName=qSavepool->selectedFile();
	delete qSavepool;

	//The real save operation
	if(!fName.isEmpty())
	{
	  	cleanup(fName.toStdString().c_str());
	}
	else
	{
	 	cleanup(0);
	}

	exit(0);
}



int main( int argc, char** argv )
{
	marsinit( &argc, argv, 0, 0, 0 );

	gac = argc;
  	gav = argv;

  	gs  = create_service(progname());
  	add_service_callback(gs,NULL,save,NULL);

  	service_run(gs);
}
