#include "picollection.h"


/** \class PICollection
 * \brief Interface to discover element groups
 * \details
 * \section PICollection_sec0 Synopsis
 * This class has only static functions so no need to create instance of the
 * %PICollection. This class provide macros to add some classes or existing
 * objects to global collection and access to them from any place of the code.
 * \snippet picollection.cpp main
 * */


PIStringList PICollection::groups() {
	PIStringList sl;
	piForeachC (Group & g, *_groups)
		sl << g.name;
	return sl;
}


PIVector<const PIObject * > PICollection::groupElements(const PIString & group) {
	piForeachC (Group & g, *_groups)
		if (g.name == group)
			return g.elements;
	return PIVector<const PIObject * >();
}


void PICollection::addToGroup(const PIString & group, const PIObject * element) {
	//piCout << "add to" << group << element;
	PIString n = element->className();
	piForeach (Group & g, *_groups)
		if (g.name == group) {
			for (int i = 0; i < g.elements.size_s(); ++i)
				if (PIString(g.elements[i]->className()) == n)
					return;
			g.elements << element;
			//piCout << "new group" << group << ", ok";
			return;
		}
	*_groups << Group(group);
	_groups->back().elements << element;
	//piCout << "new group" << group << ", ok";
}


PICollection::CollectionAdder::CollectionAdder(const PIString & group, const PIObject * element, const PIString & name) {
	if (element == 0) return;
	const_cast<PIObject * >(element)->setName(name);
	PICollection::addToGroup(group, element);
}


bool __PICollectionInitializer::_inited_(false);
PIVector<PICollection::Group> * PICollection::_groups;
