#include "wsClientMgr.h"

namespace YA
{
	wsClientMgr::wsClientMgr()
	{

	}

	wsClientMgr::~wsClientMgr()
	{

	}

	void wsClientMgr::Build( const std::vector<std::string> uri_list, const std::map<std::string, MSG_HANDLE_FUNC_TYPE>& MsgFuncList )
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		std::vector<std::string>::const_iterator vit_uri;

		int ID = 1;
		int Index = 0;
		for ( vit_uri = uri_list.begin(); vit_uri != uri_list.end(); vit_uri++ )
		{
			std::shared_ptr<wsClient> pClient = std::make_shared<wsClient>();
			pClient->init( ID, *vit_uri, MsgFuncList );
			__wsClientList.push_back( pClient );
			__uriIndexList.insert( std::make_pair( *vit_uri, Index ) );
			ID++;
			Index++;
		}
	}

	int wsClientMgr::connect( int time_out )
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			if ( __wsClientList[i]->connect( time_out ) != 0 )
			{
				char szError[1024] = { 0 };
				sprintf( szError, "[%d] websocket client failed to connect: %s.", __wsClientList[i]->GetID(), __wsClientList[i]->get_uri().c_str() );
				__LastError = szError;
				return -1;
			}
		}

		return 0;
	}

	void wsClientMgr::login()
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			__wsClientList[i]->login();
		}
	}

	void wsClientMgr::send( const std::string & Cmd, const std::string & Data )
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			__wsClientList[i]->send( Cmd, Data );
		}
	}

	std::shared_ptr<wsClient> wsClientMgr::GetClientByURI( const std::string & URI )
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		std::shared_ptr<wsClient> pClient;

		std::map<std::string, int>::iterator mit_uri;
		mit_uri = __uriIndexList.find( URI );
		if ( mit_uri != __uriIndexList.end() )
		{
			pClient = __wsClientList[mit_uri->second];
		}

		return pClient;
	}

	void wsClientMgr::close()
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			__wsClientList[i]->close();
		}
	}

	bool wsClientMgr::IsConnected()
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			if ( !__wsClientList[i]->IsConnected() )
			{
				return false;
			}
		}

		return true;
	}

	bool wsClientMgr::IsLogined()
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			if ( !__wsClientList[i]->IsLogined() )
			{
				return false;
			}
		}

		return true;
	}

	bool wsClientMgr::IsSktOpened()
	{
		std::lock_guard<std::recursive_mutex> lock( __lock );

		for ( size_t i = 0; i < __wsClientList.size() ; i++ )
		{
			if ( !__wsClientList[i]->IsSktOpened() )
			{
				return false;
			}
		}

		return true;
	}
}