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

#include <iostream>

#include <MvProtocol.h>
#include "ObjectList.h"
#include "PlotModAction.h"
#include "Root.h"

// Contructors
PmContext::PmContext(MvProtocol& proto, const MvRequest& inRequest) :
    inRequest_(inRequest),
    proto_(proto)
{
    // Empty
}

// Destructor
PmContext::~PmContext()
{
    proto_.sendReply(outRequest_);
}

// Methods
std::ostream&
PmContext::Progress()
{
    return std::cout;
}

std::ostream&
PmContext::Error()
{
    return std::cout;
}

void PmContext::RewindToAfterDrop()
{
    inRequest_.rewind();
    if (strcmp(inRequest_.getVerb(), "DROP") == 0)
        inRequest_.advance();
}

void PmContext::AddToReply(const MvRequest& reply)
{
    outRequest_ += reply;
}

#if 0
void 
PmContext::SetCurrentPresentable ( Presentable* p )
{
   presentable_ = p;
}

Presentable* 
PmContext::GetCurrentPresentable ( )
{
   return presentable_;
}
#endif

const MvRequest&
PmContext::InRequest()
{
    return inRequest_;
}

void PmContext::Execute()
{
    // The translator will attempt to add a "_VIEW" to first
    // request, no matter what the firt request is.
    FirstDataView(inRequest_("_VIEW"));

    DropX((double)inRequest_("DROP_X"));
    DropY((double)inRequest_("DROP_Y"));

    // PlotMod::Instance().watchStart("PmContext");
    while (inRequest_) {
        // Enquire the Action name
        // There is an action type associated to each
        // incoming request, as defined by the PlotModTable
        const char* actionName = ObjectList::Find("request", inRequest_.getVerb(), "action");
        PlotModAction& action = PlotModAction::Find(actionName);

        // Each action advances the request
        action.Execute(*this);
    }

    // Process pending actions
    Root::Instance().DrawTask();
}
