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

#include <iostream>
#include <stdexcept>
#include <algorithm>

#include <fcntl.h>
#include <unistd.h>

using namespace std;

static map<string,string> onOffMap;


void setParam(vector<pair<string,string> > &param,MvRequest& in,string parMv,string parObstat)
{
	const char *cval=in(parMv.c_str());

	if(cval)
  	{
		string val(cval);

		if(parMv == "all_data" || parMv == "use_ecfs_log" ||
		   parMv == "stdev" || parMv == "stat_calc" || 
		   parMv == "scat_period" || parMv == "coverage" || 
		   parMv == "use_ecfs_log" || parMv == "sta_calc" ||
		   parMv == "sta_accum" || parMv == "update_soft" ||
		   parMv == "retrieve_odb" || parMv == "feedback_clean" ||
		   parMv == "sta_clean" || parMv == "sta_plot"	)
		{
			if(onOffMap.find(val) != onOffMap.end())
			{
				val=onOffMap[val];
			}
		}
		
		else if(parMv == "odb_datalist")
		{
		  	std::transform(val.begin(),val.end(),val.begin(), ::tolower);
		}
		if(val.size() != 0)
			param.push_back(make_pair(parObstat,val));	
  	}
}


class Base : public MvService { 
protected:
	Base(char* a) : MvService(a) {};
};

class Obstat: public Base {	
public:
	Obstat() : Base("OBSTAT") {};
	void serve(MvRequest&,MvRequest&);
};

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

	string obstatScript;
	char *mvbin=getenv("METVIEW_BIN");
	if (mvbin == 0)  
	{	
		marslog(LOG_EROR,"No METVIEW_BIN env variable is defined. Cannot locate mv_obstat script!");
		setError(13);
		return;
	}
	else
	{
		obstatScript=string(mvbin) +"/mv_obstat";
	}

	//Get values from the ui
	vector<pair<string,string> > param;

	setParam(param,in,"first_cycle","FIRSTCYCLE");
	setParam(param,in,"last_cycle","LASTCYCLE");
	setParam(param,in,"expver_1","EXPVER1");
	setParam(param,in,"class_1","CLASS1");
	setParam(param,in,"stream_1","STREAM1");
	setParam(param,in,"expver_2","EXPVER2");
	setParam(param,in,"class_2","CLASS2");
	setParam(param,in,"stream_2","STREAM2");
	setParam(param,in,"all_data","LALLDATA");
	setParam(param,in,"use_ecfs_log","USE_ECFSLOG");
	setParam(param,in,"stat_def","STATDEF");
	//setParam(param,in,"user_params","STATDEF");
	//setParam(param,in,"user_flags","STATDEF");
	//setParam(param,in,"output_grib_dir","GRIBDIR");
	//setParam(param,in,"store_dir","STOREDIR");
	//setParam(param,in,"exe_dir","EXEDIR");
	//setParam(param,in,"lib_dir","LIBDIR");
	//setParam(param,in,"data_dir","DATADIR");
	setParam(param,in,"stdev","STDEV");
	setParam(param,in,"stat_merge","STAMERGE");
	setParam(param,in,"obs_format","OBSFORMAT");
	setParam(param,in,"odb_file_type","ODBFILETYPE");
	setParam(param,in,"odb_datalist","ODBDATALIST");
	setParam(param,in,"stat_calc","STACALC");
	setParam(param,in,"obstat_plot","OBSTATPLOT");
	setParam(param,in,"geogrib_average_period","GEOGRIB_AVE_PERIOD");
	setParam(param,in,"scat_period","SCAT_PERIOD");
	setParam(param,in,"coverage","LCOVERAGE");
	setParam(param,in,"use_ecf_log","USE_ECFSLOG");
	setParam(param,in,"comment","COMMENT");
	setParam(param,in,"sta_calc","STACALC");
	setParam(param,in,"sta_accum","STACALC");
	setParam(param,in,"update_soft","UPDSOFT");
        setParam(param,in,"retrieve_odb","RETRIEVEODB");
	setParam(param,in,"feedback_clean","FBKCLEAN");
	setParam(param,in,"sta_clean","STACLEAN");
	setParam(param,in,"sta_plot","STAPLOT");

	string outFile=marstmp(); //"/var/tmp/dummy-user/obstat.txt";

	FILE *fp=fopen(outFile.c_str(),"w+");
	if(fp ==0)
	{
		return;
	}
	
	for(vector<pair<string,string> >::iterator it=param.begin(); 
            it != param.end(); it++)
	{

		fprintf(fp,"%s=%s\n",(*it).first.c_str(),(*it).second.c_str());
	}

	fclose(fp);

	
	//Run obstat

	string cmd = obstatScript + " " +  outFile; 

	marslog(LOG_INFO,"Execute command: %s",cmd.c_str());

	system(cmd.c_str());

}

	  	
int main( int argc, char** argv )
{
	MvApplication theApp( argc, argv );

    	Obstat obstat;	
	
	onOffMap["ON"]="yes";
	onOffMap["OFF"]="no";
	
    	theApp.run();
}


