#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)
{
    connect(this,&MultiThreadServer::sigSendToLogger,logger,&Logger::addTextToLogger);
}

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::AutoConnection);

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

    serverLmsWidget->addClient(socketDesriptor,newClient);

    emit sigSendToLogger("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();

            ClientDeAutorization clientDeAutorization;
            clientDeAutorization.Login = login;
            serverLmsWidget->getProcessingSystem()->processingClientDeAutorization(client, clientDeAutorization);

            serverLmsWidget->removeClient(idSocket);
            delete client;
            continue;
        }

    }

    emit signalStopSendFile();
    emit sigSendToLogger("SERVER: Client " + login + " disconnected");

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

