/***************************** LICENSE START ***********************************

 Copyright 2014 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 "ReplyObserver.h"
#include "Request.h"

//=================================================================
class ReplyHandler : public MvReply {
	virtual void callback(MvRequest&);
};

void ReplyHandler::callback(MvRequest& in)
{
	ReplyObserverH *s = (ReplyObserverH*)getReference();
	if(s == 0) return;

	const char *p;
	int i = 0;
	while((p = getMessage(i++)))
	  	(*s)->message(p);

	(*s)->reply(in,getError());

	delete s;
}

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

class ProgressHandler : public MvProgress {
    void callback(MvRequest& r);
};

void ProgressHandler::callback(MvRequest& in)
{
	ReplyObserverH *s = (ReplyObserverH*)getReference();
	if(s == 0) return;

	const char *p;
	int i = 0;
	while((p = getMessage(i++)))
		(*s)->message(p);

	(*s)->progress(in);

}

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

ReplyObserver::ReplyObserver()
{
	// This will install the handler on creation of the first instance
	static ReplyHandler    replyHandler;
	static ProgressHandler progressHandler;
}

ReplyObserver::~ReplyObserver()
{
}

void ReplyObserver::callService(const string& service,const Request& r)
{
	MvApplication::callService(service.c_str(),r,new ReplyObserverH(this));
}
