/*  $Id: slot_generic.cpp,v 1.1 2004/01/28 01:17:37 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#include "API/Signals/slot_generic.h"
#include "API/Signals/slot.h"

/////////////////////////////////////////////////////////////////////////////
// CL_Slot_Generic construction:

CL_Slot_Generic::CL_Slot_Generic() : persistent(false), slot_ref_count(0), signal_ref_count(0)
{
}

CL_Slot_Generic::~CL_Slot_Generic()
{
}

/////////////////////////////////////////////////////////////////////////////
// CL_Slot_Generic attributes:

int CL_Slot_Generic::get_slot_ref() const
{
	return slot_ref_count;
}

int CL_Slot_Generic::get_signal_ref() const
{
	return signal_ref_count;
}

bool CL_Slot_Generic::is_persistent() const
{
	return persistent;
}

/////////////////////////////////////////////////////////////////////////////
// CL_Slot_Generic operations:

void CL_Slot_Generic::add_slot_ref()
{
	slot_ref_count++;
}

void CL_Slot_Generic::release_slot_ref()
{
	slot_ref_count--;
	check_delete();
}

void CL_Slot_Generic::add_signal_ref(CL_Signal *signal)
{
	connected_signals.push_back(signal);
	signal_ref_count++;
}

void CL_Slot_Generic::release_signal_ref(CL_Signal *signal)
{
	connected_signals.remove(signal);
	signal_ref_count--;
	check_delete();
}

void CL_Slot_Generic::set_persistent(bool flag)
{
	persistent = flag;
}

/////////////////////////////////////////////////////////////////////////////
//! Implementation:

void CL_Slot_Generic::check_delete()
{
	// Try remove from signals immidiately, if possible:
	if (slot_ref_count == 0 && signal_ref_count > 0)
	{
		// Prevent recursive looping (and allows us to create a helper CL_Slot object):
		slot_ref_count++;

		std::list<CL_Signal *> signals = connected_signals;
		connected_signals.clear(); // clear member list to avoid recursive loop problems

		std::list<CL_Signal *>::iterator it;
		for (it = signals.begin(); it != signals.end(); ++it)
		{
			CL_Signal *cur = (*it);
			CL_Slot slot(this);
			cur->disconnect(slot);
		}

		slot_ref_count--;
	}

	// Delete ourselves if nobody reference us anymore
	if (slot_ref_count == 0 && signal_ref_count == 0) delete this;
}
