#include "multithreadserver.h"

MultiThreadServer::MultiThreadServer(ServerLMSWidget *widget,UpdateController *updateController,
    DataParser *dataParser,Logger *logger,QObject *parent):
    QTcpServer(parent),
    serverLmsWidget(widget),
    updateController(updateController),
    dataParser(dataParser),
    logger(logger)
{

}

void MultiThreadServer::incomingConnection(qintptr socketDesriptor)
{
    ClientHandler* newClient = new ClientHandler;

    connect(this,&MultiThreadServer::sigInitClient,newClient,&ClientHandler::initialize,Qt::AutoConnection);
    connect(newClient,&ClientHandler::sigClientDisconnected,this,&MultiThreadServer::slotDisconnectClient,Qt::QueuedConnection);

    emit sigInitClient(socketDesriptor,serverLmsWidget,updateController,dataParser,logger);
    disconnect(this,&MultiThreadServer::sigInitClient,newClient,&ClientHandler::initialize);

    serverLmsWidget->addClient(socketDesriptor,newClient);

    logger->addTextToLogger("To Client: " + QString(SERVER_HELLO));
}

void MultiThreadServer::slotDisconnectClient(QString peerAddress, QString peerPort)
{
    auto clientsMap = serverLmsWidget->getClientsMap();
    QString login = "";
    qDebug() << peerAddress << " " << peerPort << " " << "disconnect";

    //Проходим все открытые сокеты, ищем нужный
    foreach(int idSocket, clientsMap.keys())
    {
        ClientHandler *client = clientsMap[idSocket];

        if(client->getClient()->getAddress() == peerAddress && client->getClient()->getPort() == peerPort)
        {
            login = client->getClient()->getLogin();
            serverLmsWidget->removeClient(idSocket);
            delete client;
            continue;
        }

    }

    emit signalStopSendFile();

    logger->addTextToLogger("SERVER: Client " + login + " disconnected");

    serverLmsWidget->slotUpdateListClients();
    serverLmsWidget->autorizationHandler(login);
}

