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

MvClient::MvClient()
	: Tasks(0)
{

}

MvClient::~MvClient()
{
	// Remove self form our tasks
	MvTask *p = Tasks;
	while(p)
	{
		MvTask *q = p->Next;
		p->Client = 0;
		p->abort();
		p = q;
	}
}

void MvClient::notify(MvTask *task)
{
	MvTask *p = Tasks;
	MvTask *q = NULL;

	// Remove from list

	while(p)
	{
		if(p == task)
		{
			if(q) q->Next = p->Next;
			else Tasks = p->Next;
			break;
		}
		q = p;
		p = p->Next;
	}

	// Call pure virtual
	endOfTask(task);
}

// Create a Task, add it to the clients list.
MvTask::MvTask(MvClient *c, const char* taskName)
	: Client(c),Next(c->Tasks),TaskName(taskName?taskName:"(?)")
{
	c->Tasks = this;
}

void MvTask::done()
{
	if(Client) Client->notify(this);
	delete this;
}

void MvTask::progress(const char *msg)
{
	if(Client) Client->progress(msg);
}

MvTask::~MvTask()
{
}
