/***************************** LICENSE START ***********************************

 Copyright 2014 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 "Metview.h"

#include "ReplyObserver.h"
#include "Request.h"

//=================================================================
class ReplyHandler : public MvReply
{
    void callback(MvRequest&) override;
};

void ReplyHandler::callback(MvRequest& in)
{
    auto* s = (ReplyObserverH*)getReference();
    if (s == nullptr)
        return;

    const char* p = nullptr;
    int i = 0;
    while ((p = getMessage(i++)))
        (*s)->message(p);

    (*s)->reply(in, getError());

    delete s;
}

//=================================================================

class ProgressHandler : public MvProgress
{
    void callback(MvRequest& r) override;
};

void ProgressHandler::callback(MvRequest& in)
{
    auto* s = (ReplyObserverH*)getReference();
    if (s == nullptr)
        return;

    const char* p = nullptr;
    int i = 0;
    while ((p = getMessage(i++)))
        (*s)->message(p);

    (*s)->progress(in);
}

//=================================================================

ReplyObserver::ReplyObserver()
{
    // This will install the handler on creation of the first instance
    static ReplyHandler replyHandler;
    static ProgressHandler progressHandler;
}

ReplyObserver::~ReplyObserver() = default;

void ReplyObserver::callService(const std::string& service, const Request& r)
{
    MvApplication::callService(service.c_str(), r, new ReplyObserverH(this));
}
