#include "MW4Headers.hpp"

#include "GroupContainer.hpp"

#include "MWObject.hpp"
#pragma warning (push)
#include <stlport\algorithm>
#pragma warning (pop)



void MechWarrior4::GroupContainer::AddObjectToGroup(MechWarrior4::MWObject& object,
													MechWarrior4::Group::identifier group)
{
	if (std::find(object.GetGroups().begin(),object.GetGroups().end(),group) != object.GetGroups().end())	// the object already belongs to the group
	{
		return;
	}

	MechWarrior4::GroupContainer::groups_container::iterator i = m_groups.find(group);
	if (i == m_groups.end())
	{
		Group g(group);
		g.AddObject(object.objectID);
		std::pair<const Group::identifier,Group> new_group(group,g);
		object.GetGroups().push_back(group);
		m_groups.insert(new_group);
	}
	else
	{
		Verify(std::find((i->second).GetElements().begin(),(i->second).GetElements().end(),object.objectID) == (i->second).GetElements().end());		// if you hit this line, the group already contains the object

		object.GetGroups().push_back(group);
		(i->second).AddObject(object.objectID);
	}
}

void MechWarrior4::GroupContainer::RemoveObjectFromGroup(MechWarrior4::MWObject& object,
														 MechWarrior4::Group::identifier group)
{
	MWObject::GroupList::iterator i = std::find(object.GetGroups().begin(),object.GetGroups().end(),group);

	if (i == object.GetGroups().end())						// the object doesn't belong to the group
	{
		return;
	}

	Verify(m_groups.find(group) != m_groups.end());			// if you hit this line, the group doesn't exist

	MechWarrior4::Group& g = m_groups.find(group)->second;
	g.RemoveObject(object.objectID);

	object.GetGroups().erase(i);
}

const MechWarrior4::Group& MechWarrior4::GroupContainer::GetGroup(MechWarrior4::Group::identifier group) const
{
	Verify(m_groups.find(group) != m_groups.end());			// if you hit this line, the group doesn't exist
	return (m_groups.find(group)->second);
}

MechWarrior4::Group& MechWarrior4::GroupContainer::GetGroup(MechWarrior4::Group::identifier group)
{
	Verify(m_groups.find(group) != m_groups.end());			// if you hit this line, the group doesn't exist
	return (m_groups.find(group)->second);
}

bool MechWarrior4::GroupContainer::GroupExists(Group::identifier group) const
{
	return (m_groups.find(group) != m_groups.end());
}
