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

MvServiceReply *MvServiceTask::ReplyHandler = NULL;

MvServiceTask::MvServiceTask(MvClient *c,const Cached& s,const MvRequest& r, const char* taskName)
	: MvTask(c, (taskName?taskName:(const char*)s) ),
	Service(s),
	Request(r)
{

	// If first time, register a reply handler
	if(!ReplyHandler)
		ReplyHandler = new MvServiceReply();
}

void MvServiceTask::run(void)
{
	MvApplication::callService(Service,Request,this);
}

MvRequest MvServiceTask::run(int& error)
{
   return MvApplication::waitService(Service,Request,error);
}

void MvServiceTask::gotReply(const MvRequest &r,err e)
{
	Reply = r;
	setError(e);

	int i = 0;
	const char *p;

	// Print messages
	while( (p = ReplyHandler->getMessage(i++)) )
		progress(p);

	// Notify client
	done();
}

void MvServiceReply::callback(MvRequest& in)
{
	MvServiceTask *task = (MvServiceTask*)getReference();
	if(task) task->gotReply(in,getError());
}
