#ifndef O2ON_P2P_H_INCLUDED
#define O2ON_P2P_H_INCLUDED

#include <boost/noncopyable.hpp>
#include <string>

#include "socket.h"

unsigned int __stdcall p2p_thread(void *data);
void sendP2PMessage(const TCPSocket& s, const std::string& method, const std::vector<char>& body);

class NodeInfo {
public:
	NodeInfo() {}
	NodeInfo(const std::string& host, unsigned short port);
	unsigned long getAddr() const { return addr_; }
	unsigned short getPort() const { return port_; }
	std::string getHost() const { return host_; }
	int getPriority() const { return priority; }
	void incPriority() { ++priority; }
	void decPriority() { --priority; }

private:
	unsigned long addr_;
	unsigned short port_;
	std::string host_;
	int priority;
};

inline bool operator<(const NodeInfo& lhs, const NodeInfo& rhs) {
	return lhs.getAddr() < rhs.getAddr();
}

inline bool operator==(const NodeInfo& lhs, const NodeInfo& rhs) {
	return lhs.getAddr() == rhs.getAddr();
}

/*!
	@brief P2P Processor
*/
class P2PProcessor : boost::noncopyable {
public:
	void setServer(TCPServer<TCPSocketBuffer<TimedTCPSocket>, P2PProcessor>* server) { server_ = server; }
	void acceptDetected();
	bool recvDetected(TCPSocketBuffer<TimedTCPSocket>& sockbuf);
	void disconnected();
	void dosomething(std::list<TCPSocketBuffer<TimedTCPSocket> >& sockets);
	void startProcessor();

	P2PProcessor(unsigned short p2p_port) : server_(0), p2p_port_(p2p_port), pretime(0)
	{ FD_ZERO(&waitingFd); }
	~P2PProcessor();

private:
//	bool parseProtocol(TCPSocketBuffer<TimedTCPSocket>& s);

	TCPServer<TCPSocketBuffer<TimedTCPSocket>, P2PProcessor>* server_;
	fd_set waitingFd;
	std::vector<SOCKET> waitingSockets;	//!< 接続待ちソケット用
	unsigned short p2p_port_;
	std::vector<NodeInfo> nodes;
	time_t pretime;
};

#endif /* O2ON_P2P_H_INCLUDED */
