#include "cloudserver.h"

CloudServer::CloudServer(DispatcherClient * c, const PIByteArray & sname) : server(c) {
	setName(sname.toHex());
	server_uuid = sname;
	CONNECTL(c, dataReadedServer, ([this](uint id, PIByteArray & ba){
		DispatcherClient * cl = index_clients.value(id, nullptr);
		if (cl) cl->sendData(ba);
	}));
}


CloudServer::~CloudServer() {
	for (auto c :clients) {
		c->close();
	}
}


PIByteArray CloudServer::serverUUID() const {
	return server_uuid;
}


void CloudServer::addClient(DispatcherClient * c) {
	clients << c;
	index_clients.insert(c->clientId(), c);
	c->sendConnected(1);
	server->sendConnected(c->clientId());
	CONNECTL(c, dataReaded, ([this, c](PIByteArray & ba){
//		piCoutObj << c->clientId() << "dataReaded";
		if (clients.contains(c)) {
			server->sendDataToClient(ba, c->clientId());
		}
	}));
}


void CloudServer::removeClient(DispatcherClient * c) {
	clients.removeOne(c);
	index_clients.removeOne(c->clientId());
	server->sendDisconnected(c->clientId());
}


PIVector<DispatcherClient *> CloudServer::getClients() {
	return clients;
}


void CloudServer::printStatus() {
	piCout << "    " << "Clients for" << server->address() << server_uuid.toHex() << ":";
	for (auto c: clients) {
		piCout << "        " << c->address() << c->clientId();
	}
//	for (auto c: clients) {
//		c->sendData(PIByteArray::fromHex("000000"));
//		server->sendDataToClient(PIByteArray::fromHex("000000"), c->clientId());
//	}
}


