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

#include "Metview.h"

#include "MessageObserver.h"

#include "Request.h"

static std::set<MessageObserver*> observers_;

class MessageHandler : public MvMessage
{
    void callback(MvRequest& r) override;
};

void MessageHandler::callback(MvRequest& in)
{
    MessageObserver::broadcast(in);
}

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

MessageObserver::MessageObserver()
{
    static MessageHandler messages;
}


MessageObserver::~MessageObserver()
{
    observers_.erase(this);
}

void MessageObserver::observe()
{
    observers_.insert(this);
}
void MessageObserver::stop()
{
    observers_.erase(this);
}


void MessageObserver::broadcast(const Request& msg)
{
    // we make a copy of the observers_ list and iterate over the copy because
    // observers could remove themselves from the observers_ list during the message()
    // method (by calling stop()), invalidating the iterator
    auto observersSafeCopy = observers_;
    for (auto j : observersSafeCopy)
        j->message(msg);
}
