///////////////////////////////////////////////////////////////////////////////
/// @file deSlaveServer.cpp
///
/// @brief 
///
/// @author trajar
///
/// This file is the intellectual property of Novus Delta, LLC.. Usage of the
/// contents of this file is subject to the Destiny3D Member License which
/// can be found at http://www.destiny3d.com.  Any other usage is prohibited.
///
/// This file is distributed "AS IS" without warranty of any kind.  Novus
/// Delta, LLC. does not guarantee the fitness of the contents of this file
/// for any particular purpose.
///
/// Copyright (C) 2001-2003 Novus Delta, LLC. All Rights Reserved.
///
/// <hr>
///                                 Change History
/// <hr>
///
/// @date Jun 2002
/// @author trajar
/// @remarks Creation
///
///////////////////////////////////////////////////////////////////////////////

#include "deSlaveServer.hpp"
#include "deNetResource.hpp"

#ifdef	_DEBUG
 #include	<crtdbg.h> 
 #define new new(_NORMAL_BLOCK,__FILE__, __LINE__)
#endif

deSlaveServer::deSlaveServer(void)
{
	m_Type			= TYPE_SLAVE_SERVER;
	m_MasterServer	= NULL;
}

deSlaveServer::~deSlaveServer(void)
{
	// ensure this is thread-safe and locked
	ENSURE_LOCK( this, this->GetSynchObject() );

	if( m_Status < STATUS_DESTROYED )
	{
		this->Destroy( NULL );
	}
}

eNetError deSlaveServer::OnInit( int pType, DWORD pFlags )
{
	eNetError r;

	// create the connection to the master connection
	r = deNet_CreateConnection( &m_MasterServer, pType, NULL );

	// set owner
	m_MasterServer->SetOwner( this );
	
	// subclass init
	if( r == CODE_OK )
		return deServer::OnInit( pType, pFlags );
	else
		return r;
}

eNetError deSlaveServer::OnDestroy( DWORD pFlags )
{
	// destroy resources
	aResources::iterator itr = m_aResources.begin();
	while( itr != NULL && itr != m_aResources.end() )
	{
		( *itr )->Destroy( NULL );
		++itr;
	}

	// close connection with master server
	m_MasterServer->Disconnect( deConnection::FLAG_FORCE_DISCONNECT );
	
	return deServer::OnDestroy( pFlags );
}

deConnection * deSlaveServer::GetConnectionByUser( hNetUser pUser )
{
	deConnection * conn = deServer::GetConnectionByUser( pUser );

	if( !conn )
	{
		if( m_MasterServer->GetConnDesc()->m_hRemoteUser == pUser )
		{
			conn = m_MasterServer;
		}
	}

	return conn;
}

eNetError deSlaveServer::AttachToMaster( deNetAddress * pAddress, DWORD pFlags )
{
	// ensure this is thread-safe and locked
	ENSURE_LOCK( this, this->GetSynchObject() );

	eNetError r;

	// connect to master server at given address
	r = m_MasterServer->ConnectTo( pAddress );

	if( r == CODE_OK )
	{
		return CODE_OK;
	}
	else
	{
		// something went wrong, kill the connection
		m_MasterServer->Disconnect( deConnection::FLAG_FORCE_DISCONNECT );

		return r;
	}
}
