/***************************** 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 <cassert>

#include "MagPlusService.h"
#include "PlotMod.h"
#include "MvLog.h"


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

MagPlusService* MagPlusService::magPlusServiceInstance_ = nullptr;

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

MagPlusService&
MagPlusService::Instance()
{
    assert(magPlusServiceInstance_ != nullptr);
    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;

    try {
        this->CallMagPlus(magReq);

        // Reset CalledFromMacro tag
        PlotMod::Instance().CalledFromMacro(false);
    }
    catch (MagicsException& e) {
        MvLog().popup().err() << e.what();
    }
}

#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
    //	MvServiceTask* serviceTask = ( MvServiceTask* ) task;

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

void MagPlusService::decode(MvRequest& req, const std::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
