#include "stdafx.h"

Connection::Connection()
{
	a_to_b_packets_buufer = new PacketsBuffer(200);
	b_to_a_packets_buufer = new PacketsBuffer(200);
	a = b = 0;
	is_last_send_to_a_success = is_last_send_to_b_success = false;
}

Connection::Connection( Router & a_ , Router & b_ )
{
	a_to_b_packets_buufer = new PacketsBuffer(200);
	b_to_a_packets_buufer = new PacketsBuffer(200);
	a = &a_;
	b = &b_;
	is_last_send_to_a_success = is_last_send_to_b_success = false;
}

Connection::~Connection()
{
	delete a_to_b_packets_buufer;
	delete b_to_a_packets_buufer;
}

void Connection::SetRouters( Router & a_ , 
							 Router & b_ )	
{ 
	a=&a_; 
	b=&b_; 
}

Router & Connection::GetA() const 
{ 
	return *a; 
}

Router & Connection::GetB() const 
{ 
	return *b; 
}

int Connection::GetCapacity() const
{
	return 2 + a_to_b_packets_buufer->GetCapacity() + b_to_a_packets_buufer->GetCapacity();
}

int Connection::GetLoad() const
{
	int load = 0;
	load += is_last_send_to_a_success ? 1 : 0;
	load += is_last_send_to_b_success ? 1 : 0;
	load += a_to_b_packets_buufer->GetLoad() + b_to_a_packets_buufer->GetLoad();
	return load;
}

int Connection::GetLoadToA() const
{
	return b_to_a_packets_buufer->GetLoad();
}

int Connection::GetLoadToB() const
{
	return a_to_b_packets_buufer->GetLoad();
}

// put packet which will send latter by SendOnePacket
bool Connection::PutOnePacketToA( Packet * packet )
	// return false iff full
{
	return b_to_a_packets_buufer->Push( packet );
}

bool Connection::PutOnePacketToB( Packet * packet )
{
	return a_to_b_packets_buufer->Push( packet );
}

bool Connection::PutOnePacket( Router & dest , Packet * packet )
{
	if( dest == *a )
		return PutOnePacketToA( packet );
	if( dest == *b )
		return PutOnePacketToB( packet );

	assert( false );
	return false;
}

Packet * Connection::SendOnePacketToA()
	// return the packet which was send or 0 if none
{
	Packet * packet = b_to_a_packets_buufer->Pop();
	if( packet )
	{
		a->SetPacketToRoute( packet );
	}

	is_last_send_to_a_success = (packet != 0);

	return packet;
}

Packet * Connection::SendOnePacketToB()
{
	Packet * packet = a_to_b_packets_buufer->Pop();
	if( packet )
	{
		b->SetPacketToRoute( packet );
	}

	is_last_send_to_b_success = (packet != 0);
	
	return packet;
}

void Connection::RemoveAllPackets()
{
	a_to_b_packets_buufer->Clear();
	b_to_a_packets_buufer->Clear();
}
