#include "stdafx.h"
#include "nwl_connection_list.h"
 
ConnectionList::ConnectionList()
{
	first = 0;
}

ConnectionList::~ConnectionList()
{
	Clear();
}

void ConnectionList::Clear()
{
	while( first )
	{
		ConnectionListEntry * new_first = first->next;
		delete first->connection;
		delete first;
		first = new_first;
	}
}

Connection & ConnectionList::AddConnection( Router & a , Router & b )
{
	assert( GetConnection( a , b ) == 0 );
	
	if( !first )
	{
		first = new ConnectionListEntry;
		first->next = 0;
		first->connection = new Connection( a , b );
		return *first->connection;
	}
	else
	{	
		ConnectionListEntry * last = first;
		while( last->next )
			last = last->next;
		last->next = new ConnectionListEntry;
		last->next->next = 0;
		last->next->connection = new Connection( a , b );
		return *last->next->connection;
	}
}

void ConnectionList::RemoveConnection( Router & a , Router & b )
{
	assert( first );

	if( first->connection->GetA() == a && first->connection->GetB() == b )
	{
		ConnectionListEntry * new_first = first->next;
		delete first->connection;
		delete first;
		first = new_first;
	}

	ConnectionListEntry * entry = first;

	while( entry->next && 
		   (entry->next->connection->GetA() != a ||
		    entry->next->connection->GetB() != b )  )
	{
		entry = entry->next;	
	}

	assert( entry->next );

	ConnectionListEntry * del_entry = entry->next;

	entry->next = del_entry->next;
	delete del_entry->connection;
	delete del_entry;
}

unsigned int ConnectionList::GetConnectionNum() const
{
	unsigned int counter = 0;
	ConnectionListEntry * entry = first;
	while( entry )
	{
		counter++;
		entry = entry->next;
	}
	return counter;
}

Connection * ConnectionList::GetConnection( const Router & a , const Router & b ) const
{
	ConnectionListEntry * entry = first;
	while( entry && 
		  (entry->connection->GetA() != a ||
		   entry->connection->GetB() != b ) )
	{
		entry = entry->next;
	}
	return entry ? entry->connection : 0;
}


