/***************************** 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 "MagPlusService.h"
#include "PlotMod.h"

// Methods for the MagPlus Service class
//
// --- METHOD:  Instance
//
// Methods to provide access to the singleton
//              MagPlus Service class 

MagPlusService *MagPlusService::magPlusServiceInstance_ = 0;

void
MagPlusService::Instance ( MagPlusService* service )
{
	magPlusServiceInstance_ = service;
}

MagPlusService&
MagPlusService::Instance ()
{
	assert (magPlusServiceInstance_ != 0 );
	return *magPlusServiceInstance_;
}

MagPlusService::MagPlusService () : magplus_(new magics::MagPlus())
{
//	magplus_->registerObserver(this);
}

void
MagPlusService::SetRequest ( const MvRequest& req )
{
     // Build request to be sent to ToolsPlus application
     MvRequest magReq = "MAGPLUS";
     magReq = magReq + req;

     cout << "DEBUG> >>>>>>>>>>>>>>> Calling Magics >>>>>>>>>>>>>>>" << endl;
     magReq.print();

     this->CallMagPlus ( magReq );

     // Reset CalledFromMacro tag
     PlotMod::Instance().CalledFromMacro(false);
}

#if 0
void
MagPlusService::CallMagPlusRedraw ( MvRequest& in )
{
	// Call MagPlus to process the request
	MvRequest answer;
	magplus_->redraw(in,answer);
}
#endif

void
MagPlusService::endOfTask ( MvTask* task )
{
	// Empty reply from Eps Tool goes directly to RegisterToolAction
//	cout << " endOfTask" << endl;
//	MvServiceTask* serviceTask = ( MvServiceTask* ) task;

//	MvRequest replyRequest = serviceTask->getReply();
//	replyRequest.print();

        cout << "DEBUG> MAGPLUSSERVICE::endOfTask" << endl;
}

void
MagPlusService::decode( MvRequest& req, const string& sjson )
{
   // Structure MvMagRequest requires that the input MvRequest has a Verb
   if ( !req.getVerb() )
      req.setVerb("GCoord");

   MvMagRequest magReq(req);

   // Translate json string to a MagRequest
   magplus_->decode(magReq,sjson);

   // Get the equivalent MvRequest
   req = magReq.getRequest();
}

#if 0
void
MagPlusService::RegisterObserver(MagicsObserver* observer)
{
	magplus_->registerObserver(observer);
}

void
MagPlusService::UnRegisterObserver(MagicsObserver* observer)
{
	magplus_->unregisterObserver(observer);
}
#endif
