//
// C++ Implementation: qgarbagecollector
//
// Description: Garbage Collector class for Qt4
//
// Copyright: (c) AMD, 2005
// Author: Konrad Rosenbaum <konrad.rosenbaum@amd.com>
//
// with permission from AMD refactored by
// (c) Konrad Rosenbaum, 2005
// published under the GNU GPL, v.2


#include "qgarbagecollector.h"

QGarbageCollector::QGarbageCollector(QObject*child,QObject*supervisor)
{
	addChild(child);
	addSupervisor(supervisor);
}

QGarbageCollector::~QGarbageCollector()
{
	for(int i=0;i<children.size();i++){
		//make sure we don't double kill ourselves through removeChild
		QObject*c=children[i];
		disconnect(c,SIGNAL(destroyed(QObject*)),this,SLOT(removeChild(QObject*)));
		//actually delete child
		delete c;
	}
}

void QGarbageCollector::addChild(QObject*c)
{
	if(c && !children.contains(c)){
		children.append(c);
		connect(c,SIGNAL(destroyed(QObject*)),this,SLOT(removeChild(QObject*)));
	}
}

void QGarbageCollector::removeChild(QObject*c)
{
	//remove child from GC
	disconnect(c,SIGNAL(destroyed(QObject*)),this,SLOT(removeChild(QObject*)));
	children.removeAll(c);
	//if no more children, pray and fade into oblivion
	if(children.size()<=0)
		delete this;
}

void QGarbageCollector::addSupervisor(QObject*s)
{
	if(s && !supervisors.contains(s)){
		supervisors.append(s);
		connect(s,SIGNAL(destroyed(QObject*)),this,SLOT(removeSupervisor(QObject*)));
	}
}

void QGarbageCollector::removeSupervisor(QObject*s)
{
	//remove this supervisor
	disconnect(s,SIGNAL(destroyed(QObject*)),this,SLOT(removeSupervisor(QObject*)));
	supervisors.removeAll(s);
	//warn the world that this universe is collapsing
	if(supervisors.size()<=0)
		emit aboutToDelete();
	//check whether universe was rescued, then collapse
	if(supervisors.size()<=0)
		delete this;
}

bool QGarbageCollector::isChild(QObject*c)
{
	return children.contains(c);
}

bool QGarbageCollector::isSupervisor(QObject*s)
{
	return supervisors.contains(s);
}
