/***************************** 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 "Met3D.h"
#include "mars.h"

Met3D::Met3D(const char* kw): MvService(kw)
{
   //empty
}

Met3D::~Met3D()
{
   //empty
}

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

   // Get information from the user interface
   if ( !GetInputInfo(in) )
      return;

   // Execute application
   execute();

   return;
}

bool Met3D::GetInputInfo(MvRequest& in)
{
   // Get data information from UI
   string str;
   if ( (const char*)in("SOURCE") && (strcmp((const char*)in("SOURCE"),"OFF") && strcmp((const char*)in("SOURCE"),"off")) )
   {
      path_ = (const char*)in("SOURCE");
   }
   else
   {
      // Get information from the icon
      MvRequest dataRequest;
      in.getValue(dataRequest,"DATA");
      if ( !in.countValues("DATA") || !dataRequest.countValues("PATH") )
      {
         setError(1, "No Data files specified...");
         return false;
      }

      // Build the path information by concatenating the respective
      // path information from each data request
      bool first = true;
      while ( dataRequest )
      {
         if (first)
         {
            path_ = (const char*)dataRequest("PATH");
            first = false;
         }
         else
            path_ += string(";") + (const char*)dataRequest("PATH");

         dataRequest.advance();
      }
   }

   // Get the pipeline file path
   // If the pipeline file is not given in the user interface then
   // check the correspondent environment variable
   pipeline_file_ = "";
   if ( (const char*)in("PIPELINE_FILE") && 
        strcmp((const char*)in("PIPELINE_FILE"),"DEFAULT") != 0 )
      pipeline_file_ = (const char*)in("PIPELINE_FILE");
   else if ( (const char*)getenv("MV_MET3D_PIPELINE_FILE") )
      pipeline_file_ = (const char*)getenv("MV_MET3D_PIPELINE_FILE");

   // Get the frontend file path
   // If the path is not given in the user interface then
   // check the correspondent environment variable
   frontend_file_ = "";
   if ( (const char*)in("FRONTEND_FILE") && 
        strcmp((const char*)in("FRONTEND_FILE"),"DEFAULT") != 0 )
      frontend_file_ = (const char*)in("FRONTEND_FILE");
   else if ( (const char*)getenv("MV_MET3D_FRONTEND_FILE") )
      frontend_file_ = (const char*)getenv("MV_MET3D_FRONTEND_FILE");

   return true;
}

void Met3D::execute()
{
   // Build command line (assumes that module met3D is already loaded)
   // Add data path
   string cmd("env --unset=GRIB_DEFINITION_PATH --unset=LD_LIBRARY_PATH met3D --metview --path=");
//   cmd = "met3D --pipeline=/home/graphics/cgk/Downloads/pipeline-iain.cfg --frontend=/home/graphics/cgk/Downloads/frontend-iain.cfg";
   if ( path_[0] == '\"' )
      cmd += path_ ;
   else
      cmd += "\"" + path_ + "\"";

   // Add configuration files, if exists
   if ( !pipeline_file_.empty() )
      cmd += " --pipeline=" + pipeline_file_;

   if ( !frontend_file_.empty() )
      cmd += " --frontend=" + frontend_file_;

//cout << "Met3D command: " << cmd << endl;

   // Execute command line
   int ret = system(cmd.c_str());	

   // If the script failed read log file and
   // write it into LOG_EROR
   if(ret == -1 || WEXITSTATUS(ret) != 0)
   {
      cout << "EXECUTION ERROR" << endl;
#if 0
      ifstream in(logFile.c_str());
      string line;
		
		    if(WEXITSTATUS(ret) == 1)
	    	{		
			      marslog(LOG_EROR,"Failed to startup VAPOR!");
         while(getline(in,line))
         {
				        marslog(LOG_EROR,"%s",line.c_str());
			      }
			      in.close();
			      setError(13);
			      return;
      }
      else if(WEXITSTATUS(ret) > 1)
      {		
         marslog(LOG_EROR,"VAPOR startup failed with exit code: %d !",WEXITSTATUS(ret));
         while(getline(in,line))
         {
            marslog(LOG_EROR,"%s",line.c_str());
         }
         in.close();
         setError(13);
         return;
      }
#else
      setError(13);
      return;
   }
#endif
}


//--------------------------------------------------------

int main(int argc,char **argv)
{
   MvApplication theApp(argc,argv);
   Met3D met3d("MET3D");

   // The applications don't try to read or write from pool, this
   // should not be done with the new PlotMod.
   //a.addModeService("GRIB", "DATA");
   //c.saveToPool(false);
   //met3d.saveToPool(false);

   theApp.run();
}
