/***************************** 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 <string>
using std::string;

#include <Metview.h>


#ifndef MacroRunTask_H
#include "MacroRunTask.h"
#endif

#ifndef IconObject_H
#include "IconObject.h"
#endif

#ifndef Log_H
#include "Log.h"
#endif


#ifndef Request_H
#include "Request.h"
#endif

#ifndef Service_H
#include "Service.h"
#endif
#ifndef Action_H
#include "Action.h"
#endif

#ifndef IconObject_H
#include "IconObject.h"
#endif
#ifndef IconClass_H
#include "IconClass.h"
#endif

#ifndef MacroEditor_H
#include "MacroEditor.h"
#endif

//=================================================================

MacroRunTask::MacroRunTask(MacroEditor& editor,const Action& action,IconObject* o,bool trace):
	action_(action),
	editor_(editor),
	object_(o),
	trace_(trace)
{
}

MacroRunTask::~MacroRunTask()
{
	cout << "MacroRunTask::~MacroRunTask " << *object_ << endl;
}

void MacroRunTask::start()
{
	MvRequest r   = object_->fullRequest();
	const char* null = 0;
	Service* service = object_->iconClass().service(action_);

	if(null == r("_NAME"))    r("_NAME")    = object_->fullName().c_str();
	if(null == r("_CLASS"))   r("_CLASS")   = object_->className().c_str();
	if(null == r("_ACTION"))  r("_ACTION")  = action_.name().c_str();
	if(null == r("_SERVICE")) r("_SERVICE") = service->name().c_str();

	r("_TRACE") = trace_;

	cout << " ---> send " << *this << endl;
	r.print();

	callService(service->name().c_str(),r);

	cout << " <--- send " << *this << endl;
}

void MacroRunTask::reply(const Request& r,int err)
{
	if(err) 
		Task::failure();
	else 
		Task::success(r);
	
}

void MacroRunTask::progress(const Request& r)
{
}

void MacroRunTask::message(const string& msg)
{
	static string cr("\n");
	if(!stopped_) {
		editor_.progress(msg);
		editor_.progress(cr);
	}
}

void MacroRunTask::print(ostream& s) const
{
  	s << "MacroRunTask[" 
      << action_.name() 
	  << ","  
	  << action_.mode() 
	  << ","
      << *object_ 
	  << "]";

}

