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

Queue ProcessingQueue::gQueue;
QIter ProcessingQueue::gIter;

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

PElem::PElem(request* r, Service* s) :
    QElem(r),
    svc_(s)
{
}

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

PElem::~PElem() = default;

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

void ProcessingQueue::Append(request* r, Service* s)
{
    Append(new PElem(r, s));
}

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

// When a module exits, remove all refernec to it and
// send an error to the calling modules.

void ProcessingQueue::RemoveAll(Service* s)
{
    PElem* q;

    Rewind();
    while ((q = Next()) != nullptr) {
        if (q->Module() == s) {
            marslog(LOG_INFO, "Service %s died before completing the request", s->Name());
            Service::ReplyFail("Service %s died before completing the request",
                               s->Name(),
                               q->Request());
            Remove(q);
            Event::AbortIfBatch("ProcessingQueue::RemoveAll()");
        }
    }
}

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

void ProcessingQueue::NotifyMonitor()
{
    PElem* q;

    Rewind();
    while ((q = Next()) != nullptr) {
        Service* s = q->Module();
        s->NotifyMonitor("SERVICE", q->Request());
    }
}

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

// A request has completed, remove it from the queue

void ProcessingQueue::Remove(request* r)
{
    const char* reqid = get_value(r, "REQ_ID", 0);
    PElem* q;

    Rewind();
    while ((q = Next()) != nullptr) {
        const char* id = get_value(q->Request(), "REQ_ID", 0);
        if (id == reqid)
            Remove(q);
    }
}

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

Service* ProcessingQueue::Followup(request* r, Service* s)
{
    const char* reqid = get_value(r, "REQ_ID", 0);
    PElem* q;

    Rewind();
    while ((q = Next()) != nullptr) {
        const char* id = get_value(q->Request(), "REQ_ID", 0);
        if (id == reqid) {
            Service* a = q->Module();
            q->Reparent(s);
            return a;
        }
    }
    return nullptr;
}
