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

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

Queue::~Queue()
{
}

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

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

	enable();
}

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

	if(active_ == 0 && 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*)
{
	if(owner_) owner_->notifyError();
	done();
}

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