#ifndef DISPATCHERSERVER_H
#define DISPATCHERSERVER_H

#include "cloudserver.h"
#include "pitimer.h"

class TileList;


class DispatcherServer: public PIObject {
	PIOBJECT(DispatcherServer)

public:
	DispatcherServer(PINetworkAddress addr);
	~DispatcherServer();
	void start();

	void updateConnectionsTile(TileList * tl);
	void updateServersTile(TileList * tl, PISet<const DispatcherClient *> servers = PISet<const DispatcherClient *>());
	void updateClientsTile(TileList * tl, PISet<const DispatcherClient *> servers = PISet<const DispatcherClient *>());
	const DispatcherClient * getConnection(int index);
	const DispatcherClient * getServer(int index);
	PISet<const DispatcherClient *> getServers(PISet<int> ids);
	void setMaxConnections(uint max_count);
	uint maxConnections() const { return max_connections; }
	EVENT_HANDLER0(void, picoutStatus);

	void startWatchdog();

private:
	EVENT_HANDLER1(void, newConnection, PIEthernet *, cl);
	EVENT_HANDLER1(void, disconnectClient, DispatcherClient *, client);
	EVENT_HANDLER0(void, cleanClients);

	PIEthernet eth;
	PIVector<DispatcherClient *> clients;
	PIMap<PIByteArray, CloudServer *> c_servers;
	PIMap<const DispatcherClient *, CloudServer *> index_c_servers;
	PIMap<const DispatcherClient *, CloudServer *> index_c_clients;
	PISet<DispatcherClient *> rm_clients;
	PISet<DispatcherClient *> rmrf_clients;
	PIVector<CloudServer *> rmrf_servers;
	PITimer timeout_timer;
	PIMutex map_mutex;
	std::atomic_int wd_cnt = {0};
	uint client_gid;
	uint max_connections;
};

#endif // DISPATCHERSERVER_H
