/***************************** 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 "Runnable.h"
#include "Metview.h"

#include <QTimer>
#include <set>

#include <cassert>

using Set = std::set<Runnable*>;
static Set runnables;

/* do a process in the "background" */

void Runnable::slotWork()
{
    // Copy as Runnable may be removed

    Set s = runnables;
    int active = 0;

    for (auto j : s) {
        if (j->actived_) {
            active++;
            j->run();
        }
    }

    if (active != 0) {
        // Find an exisiting runnable and set the timer for it!
        auto j = runnables.begin();
        if (j != runnables.end()) {
            QTimer::singleShot(0, (*j), SLOT(slotWork()));
        }
        else {
            // This should not happen!
            assert(0);
        }
    }
}

Runnable::Runnable() :
    actived_(false)
{
    runnables.insert(this);
}

Runnable::~Runnable()
{
    runnables.erase(this);
}

void Runnable::enable()
{
    if (actived_)
        return;

    QTimer::singleShot(0, this, SLOT(slotWork()));

    actived_ = true;
}

void Runnable::disable()
{
    actived_ = false;
}
