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

#include "Task.h"
#include "IconObject.h"
#include "Log.h"
#include "Request.h"

Queue::Queue(IconObject* owner) :
    owner_(owner),
    active_(nullptr)
{
}

Queue::~Queue() = default;

void Queue::ownerGone()
{
    owner_ = nullptr;
    enable();
}

void Queue::push(Task* t)
{
    t->add(this);
    tasks_.emplace_back(t);

    enable();
}

void Queue::run()
{
    if (owner_ == nullptr && active_ == nullptr) {
        delete this;
        return;
    }

    if (active_ == nullptr && tasks_.size() != 0) {
        active_ = tasks_.front();
        tasks_.pop_front();
        if (owner_)
            owner_->notifyWaiting();
        active_->start();
    }

    if (tasks_.size() == 0)
        disable();
}

void Queue::success(Task*, const Request&)
{
    if (owner_)
        owner_->notifyReady();
    done();
}

void Queue::failure(Task*, const Request& r)
{
    if (owner_) {
        MvRequest req = r;  // to remove compilation warning message
        std::string err;
        if (req.getError(err))
            Log::error(owner_) << err.c_str() << std::endl;

        owner_->notifyError();
    }
    done();
}

void Queue::done()
{
    active_ = nullptr;
}
