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

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

#include <sstream>

#include "MvScm.h"

using namespace std;


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

class RttovRun: public Base {	
public:
	RttovRun() : Base("RTTOV_RUN") {};
	void serve(MvRequest&,MvRequest&);
};

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

    std::string errTxt;

	//Find out rttov script path
    std::string rttovScript;
	char *mvbin=getenv("METVIEW_BIN");
	if (mvbin == 0)  
	{	
		marslog(LOG_EROR,"No METVIEW_BIN env variable is defined. Cannot locate script mv_rttov_run!");
		setError(13);
		return;
	}
	else
	{
		rttovScript=string(mvbin) +"/mv_rttov_run";
	}
	

	//Create  tmp dir for the flextra run
    std::string tmpPath;
	if(!metview::createWorkDir("rttov",tmpPath,errTxt))
	{
		marslog(LOG_EROR,"%s",errTxt.c_str());
		setError(13);
		return;
	}
	
	//RttovRun exe
	string exe;	
    if(!in.getPath("RTTOV_EXE_PATH",exe,true))
	{		
		setError(13);
		return;
	}	
	if(exe.empty())
	{
	  	exe="_UNDEF_";
	}	

        //---------------------------------------
	// Input data
	//---------------------------------------
	
	string data;
	if(!in.getPath("RTTOV_INPUT_DATA","RTTOV_INPUT_DATA_PATH",data,false,errTxt))
	{
		marslog(LOG_EROR,"%s",errTxt.c_str());
		setError(13);
		return;
	}	
	
	//-------------------------
	// Level num
	//-------------------------
	
	int levelNum=MvScm::modelLevelNum(data);
	if(levelNum == -1)
	{  
		marslog(LOG_EROR,"Could not read number of levels from input file!");
		setError(13);
		return;	
	}
	
	stringstream sst;
  	sst << levelNum;
   	string nlev=sst.str();   
	
	//--------------------------------------
	// Sensor (channels + coefficients)
	//--------------------------------------
	
	const char *sensor=in("RTTOV_SENSOR");
	
	string ch="_UNDEF_";
	string coeff="_UNDEF_";
	if(sensor && strcmp(sensor,"CUSTOM") == 0)
	{		  		
	  		  	  
	  	//Channels file
	  	if(!in.getPath("RTTOV_CHANNELS","RTTOV_CHANNELS_PATH",ch,true,errTxt))
		{
			marslog(LOG_EROR,"%s",errTxt.c_str());
			setError(13);
			return;
		}	
	
		//Coeff file
		if(!in.getPath("RTTOV_COEFFICIENTS","RTTOV_COEFFICIENTS_PATH",coeff,true,errTxt))
		{
			marslog(LOG_EROR,"%s",errTxt.c_str());
			setError(13);
			return;
		}				
	}
	
	//-------------------------
	// Angles
	//-------------------------
	
	double sat_z,sat_az,solar_z,solar_az;
	
	in.getValue(sat_z,"RTTOV_SATELLITE_ZENITH_ANGLE");
	in.getValue(sat_az,"RTTOV_SATELLITE_AZIMUTH_ANGLE");
	in.getValue(solar_z,"RTTOV_SOLAR_ZENITH_ANGLE");
	in.getValue(solar_az,"RTTOV_SOLAR_AZIMUTH_ANGLE");
	
	//---------------------------
	// Prepare input file
	//---------------------------
	
	string inFile=tmpPath + "/rttov_in.txt";
	bool useOzone=(sensor && strcmp(sensor,"IASI") == 0)?true:false;
	if(MvScm::createRttovInput(data,inFile,sat_z,sat_az,solar_z,solar_az,useOzone,errTxt) == false)
	{
	  	marslog(LOG_EROR,"Could not generate RTTOV input file!");
		marslog(LOG_EROR," --> %s",errTxt.c_str());
	  	setError(13);
		return;
	}  
	
	//-------------------------
	// Run the model
	//-------------------------
		
	string resFileName="rttov_out.txt";
	string resFile=tmpPath + "/" + resFileName;
	
	string logFileName="log.txt";
	string logFile=tmpPath + "/" + logFileName;
	
        //Run the scm script
	string cmd = rttovScript + " \"" + tmpPath + "\" \"" + exe  + "\" \"" + inFile + "\" \"" +  nlev +  "\" \"" + sensor + "\" \"" +  ch +  "\" \""  + coeff + "\" \"" + logFileName + "\" \"" + resFileName + "\""; 

	//marslog(LOG_INFO,"Execute command: %s",cmd.c_str());
	
	int ret=system(cmd.c_str());	
	
	bool runFailed=false;
	
	//If the script failed read log file and
	//write it into LOG_EROR
	if(ret == -1 || WEXITSTATUS(ret) != 0)
	{		
		ifstream in(logFile.c_str());
		string line;

		if(WEXITSTATUS(ret) == 255)
		{
		  	marslog(LOG_WARN,"Warnings were generated during RTTOV run!");
		}  		
		else if(WEXITSTATUS(ret) == 1)
		{		
			marslog(LOG_EROR,"Failed to perform RTTOV run!");
			runFailed=true;
		}
		else if(WEXITSTATUS(ret) > 1)
		{		
			marslog(LOG_EROR,"RTTOV run failed with exit code: %d !",WEXITSTATUS(ret));
			runFailed=true;
		}		
	}
	
	//Log locations are always printed!!
	
	if(runFailed)
	{
	  	marslog(LOG_EROR,"Log files are available at:");
		marslog(LOG_EROR,"---------------------------");
		marslog(LOG_EROR," (STDOUT)  %s",logFile.c_str());	
		string msg=tmpPath + "/fort.20";
		marslog(LOG_EROR," (fort.20) %s",msg.c_str());
	}  
	else
	{  
		marslog(LOG_INFO,"Log files are available at:");
		marslog(LOG_INFO,"---------------------------");
		marslog(LOG_INFO," (STDOUT)  %s",logFile.c_str());	
		string msg=tmpPath + "/fort.20";
		marslog(LOG_INFO," (fort.20) %s",msg.c_str());
	}
	
	//Retrun if run failed!!
	if(runFailed)
	{
		setError(13);  	
		return;
	}
	
	//---------------------------------------------------
	// Copy the output into the user-defined location
	//---------------------------------------------------
	
	/*if(!userResFile.empty())
	{
	  	const char *dn=dirname(userResFile.c_str());
	  	cmd="mkdir -p " + string(dn) + "; cp -f " + resFile + " " +  userResFile;
			
	  	stringstream outStream;
		stringstream errStream;
		shellCommand(cmd,outStream,errStream);
		
		if(!errStream.str().empty())
		{
			marslog(LOG_EROR,"");
			marslog(LOG_EROR,"Could not copy ouput file to target location!");  
		        marslog(LOG_EROR,"This command:");
			marslog(LOG_EROR,"   %s",cmd.c_str());
			marslog(LOG_EROR,"failed with this error:");
			marslog(LOG_EROR,"   %s",errStream.str().c_str());
			setError(13);
		}
	}*/
		
	//------------------------------------------
	//Set out request
	//------------------------------------------
	
	out=MvRequest("RTTOV_OUTPUT_FILE");
	out("PATH")=resFile.c_str();
	
	cout << tmpPath << endl;
	out.print();
}

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

    	RttovRun rttovRun;	
	
    	theApp.run();
}

