/***************************** 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 "GenAppService.hpp"
#include "ObjectList.h"
#include "PlotMod.h"
#include "MvLog.h"

// Methods for the GenApp Action class
//

GenAppService&
GenAppService::Instance()
{
    static GenAppService genAppServiceInstance_;
    return genAppServiceInstance_;
}

GenAppService::GenAppService() = default;

GenAppService::~GenAppService() = default;

// --- CallGenApp
//
// --- PURPOSE: Calls GenApp asking for an editing definition
//
// --- INPUT:   (a) Callback procedure to be called when the requested
//                  is received back from GenApp
//              (b) Request to be sent to GenApp for editing
//
// --- NOTE:    More than one editing action can takes place at a time.
//              A Map facilities will take care the relationship between
//              each editing request and the related callback

bool GenAppService::CallGenApp(MvCallbackBase* callback, MvRequest& defRequest)
{
    // require ( callback != 0);
    if (!callback)
        return false;

    // Call a Request which is sent directly to MetviewUI
    MvRequest editRequest("EDIT");

    // It seems that there is no need to expand the request.
    // If it is needed then the hidden parameters need to be copied because
    // the expand function does not copy them automatically.
    // Expand the definition request
    //  MvRequest expandedRequest = ObjectList::ExpandRequest ( defRequest, 0 );
    //  expandedRequest("_*") = defRequest("_*");

    //  editRequest.setValue ("DEFINITION", expandedRequest );
    editRequest.setValue("DEFINITION", defRequest);

    // Create a new task
    char* desktop = getenv("MV_DESKTOP_NAME");
    if (desktop == nullptr) {
        MvLog().popup().warn() << "uPlot GenAppService::CallGenApp-> environmental variable MV_DESKTOP_NAME not defined";
        return false;
    }

    std::string desktopName(desktop);
    auto* task = new MvServiceTask(this, desktop, editRequest);

    // Put the task in the map
    callbackMap_[task] = callback;

    // Call GenApp to process the request
    task->run();

    return true;
}


void GenAppService::endOfTask(MvTask* task)
{
    // Retrieve the reply request
    auto* serviceTask = (MvServiceTask*)task;

    MvRequest replyRequest = serviceTask->getReply();

    // Find the associated callback on the map
    auto it = callbackMap_.find(serviceTask);
    if (it == callbackMap_.end())
        return;

    // Execute the callback procedure
    (*it).second->ExecuteCallback(replyRequest);

    callbackMap_.erase(it);  // clean up
}
