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

#include "Event.h"
#include "MvMiscellaneous.h"

Queue WaitingQueue::gQueue;
QIter WaitingQueue::gIter;

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

WElem::WElem(request* r, const char* name) :
    QElem(r),
    fail_(0),
    late_(0),
    start_(time(0)),
    when_(0),
    name_(strcache(name))
{
}

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

void WElem::Update()
{
    when_ = time(0);
    if (when_ - start_ > 60 * 5)  // 5 Minutes
        fail_ = 1;
}

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

WElem::~WElem()
{
    strfree(name_);
}

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

void WaitingQueue::Append(request* r, const char* name)
{
    WElem* q;

    // Check if a request for the same module in in

    int in = 0;
    if (Service::Find(name) == 0) {
        Rewind();
        while ((q = Next()) != 0)
            if (q->Name() == name)
                in = 1;
    }


    Append(q = new WElem(r, name));
    if (in)
        q->Update();
}

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

void WaitingQueue::Later(request* r, const char* name)
{
    auto* p = new WElem(r, name);
    p->Update();
    p->Late(1);
    Append(p);
}

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

void WaitingQueue::Process()
{
    WElem* q;

    // First check for modules that are now running

    time_t now = time(0);

    Rewind();
    while ((q = Next()) != 0) {
        Service* s = Service::Find(q->Name());

        if (s && !s->Busy()) {
            if (!q->Late() || (now - q->When() > 2))  // 2 sec.
            {
                s->CallService(q->Request());
                Remove(q);
            }
        }
    }

    // Now look for modules to start

    Rewind();
    while ((q = Next()) != 0)
        if (Service::Find(q->Name()) == 0) {
            if (now - q->When() > 5)  // 5 sec.
            {
                // Update other requests for the same moduel

                QIter iter(gQueue);
                WElem* p;

                while ((p = (WElem*)iter()) != 0)
                    if (p->Name() == q->Name())
                        p->Update();

                if (StartModule(q->Name()) != 0)
                    q->Fail(1);
            }
        }

    // Look for failed requests

    Rewind();
    while ((q = Next()) != 0) {
        if (q->Fail()) {
            Service::ReplyFail("Cannot start service %s",
                               q->Name(), q->Request());
            Remove(q);
        }
    }
}

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

void WaitingQueue::NotifyMonitor()
{
    WElem* q;

    Rewind();
    while ((q = Next()) != 0) {
        const char* x = get_value(q->Request(), "SOURCE_REF", 0);
        long ref = x ? atol(x) : -1;
        Service* s = Service::Find(ref);
        if (s)
            s->NotifyMonitor("WAIT", q->Request());
    }
}

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

int WaitingQueue::StartModule(const char* name)
{
    static char* service = strcache("service");
    request* r = mars.setup;

    while (r) {
        if (r->name == service) {
            const char* nme = get_value(r, "name", 0);
            const char* cmd = get_value(r, "cmd", 0);
            if (nme && cmd && (name == nme)) {
                char buf[1024];
                marslog(LOG_INFO, "Starting service: %s", nme);
                marslog(LOG_INFO, "With command    : %s", cmd);

                const char* mvSlog = getenv("MV_SLOG");
                if ((strcmp(name, "mars") == 0 && metview::isForceMarsLogSet()) ||
                    (mvSlog && strcmp(mvSlog, "yes") == 0)) {
                    //-- do not block module output --//
                    sprintf(buf, "exec %s </dev/null &", no_quotes(cmd));
                }
                else {
                    //-- redirect module output to /dev/null --//
                    sprintf(buf, "exec %s >/dev/null 2>&1 </dev/null &",
                            no_quotes(cmd));
                }

                if (system(buf) != 0) {
                    Service::UserMessage(
                        "Failed to start service %s"
                        " with command %s",
                        name, buf);
                    return 1;
                }
                return 0;
            }
        }
        r = r->next;
    }
    marslog(LOG_EROR, "Cannot find service %s", name);
    Service::UserMessage("Cannot find service %s", name);
    return 1;
}
