/*
	AramakiOnline
	Copyright (C) 2008 superbacker

	This program is free software; you can redistribute it and/or modify it under the terms
	of the GNU General Public License as published by the Free Software Foundation;
	either version 3 of the License, or (at your option) any later version.

	This program 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 General Public License for more details.

	You should have received a copy of the GNU General Public License along with this
	program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef P2PNETWORK_H_
#define P2PNETWORK_H_

#include <wx/wx.h>
#include <wx/socket.h>
#include "Point3d.h"
#include "Map.h"
#include "Node.h"

class Map;

class P2PNetwork : public wxEvtHandler {
	//ID
	static const int ID_SOCKET_SERVER=1;

	Nodes nodes;

	//サーバーソケット
	wxSocketServer *serverSocket;
	//接続エラーフラグ
	bool error;
	//ノードリストロック用Mutex
	wxMutex nodeListLockMutex;

	//サーバーソケットイベント
	void onServerSocketEvent(wxSocketEvent &event);
	//ポート開放チェック
	void portCheck(uint16_t port);
	//初期ノードを取得
	bool getInitNode(const wxString &bootstrapScriptUrl,wxString &initNodeHost,uint16_t &initNodePort);
	//ネットワークに自身を登録
	void registerNetwork(const wxString &bootstrapScriptUrl,uint16_t listenPort);

	P2PNetwork(const P2PNetwork &);
	void operator=(const P2PNetwork &);

	DECLARE_EVENT_TABLE()
public:
	//ネットワークに接続
	P2PNetwork(uint16_t listenPort,const wxString &bootstrapScriptUrl);
	//ネットワークから切断
	~P2PNetwork();
	//位置変更を通知
	void sendPosition(const Point3d &position);
	//発言を通知
	void sendMessage(const wxString &message);
	//名前を通知
	void sendName(const wxString &name);
	//マップ移動を通知
	void sendMap(const Map &map);
	//キャラクタを描画
	void renderCharacter();
	//Node からのイベントを処理する
	void onSet(class SetEvent &event);

	void ready();

	inline bool isError() const  {
		return error;
	}
};

#endif /* P2PNETWORK_H_ */
