/***************************** 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 "PlotModService.h"
#include "MvRequest.h"
#include "PlotModTask.h"
#include "Task.h"
#include "Page.h"
#include "PlotMod.h"
#include "Root.h"

PlotModService::PlotModService ( const char *serviceName,
				 PlotModView *view ):
	serviceName_( serviceName ),
	view_( view )
{
}

PlotModService::PlotModService ( PlotModView *view ):
	view_( view )
{
}

PlotModService::PlotModService ( const PlotModService &old) :
	serviceName_(old.serviceName_),
	view_((PlotModView*)this)
{
}

PlotModService::~PlotModService()
{
}

void PlotModService::endOfTask (MvTask* task)
{
    MvServiceTask* serviceTask = (PlotModTask* ) task;
    MvRequest replyRequest = serviceTask->getReply();

    if ( serviceTask->getError() == 0 )
    {
        // Get the parent data unit id.
        MvRequest contextRequest = replyRequest.getSubrequest ("_CONTEXT");
        if ( contextRequest )
            view_->ParentDataUnitId(contextRequest("_PARENT_DATAUNIT_ID") );

        // Call the presentable and insert the data
        view_->InsertDataRequest ( replyRequest );

        // Register drawing task
        int pageId = view_->Owner().Id();
        Presentable* pageNode = Root::Instance().FindBranch (pageId);
        pageNode->HasDrawTask(true);
        pageNode->DrawTask(); //Draw
    }
    else
    {
        string title = "Error from "; title += serviceName_.c_str();
        PlotMod::Instance().UserMessage(title);
    }

    msg_.erase();
}
