#include "processingsystem.h"

#include <clienthandler.h>

ProcessingSystem::ProcessingSystem(QObject *parent):
    QObject(parent)
{

}

void ProcessingSystem::initialize(DataParser *dataParser, ServerLMSWidget *server,InstructorsAndTraineesWidget *instructorsAndTrainees)
{
    this->server = server;
    this->dataParser = dataParser;
    this->pInstructorsAndTrainees = instructorsAndTrainees;
}

void ProcessingSystem::processingClientAutorization(ClientHandler *client, ClientAutorization clientAutorization)
{
    if(server->getStateBlockAutorization() == blocked)
    {
        QByteArray arrayAnswer = dataParser->xmlAnswer_notify(NOTIFY_SERVER_BLOCKED);
        client->sendXmlAnswer(arrayAnswer);

        QString str = QString(arrayAnswer);
        emit sigLogMessage("To Client: " + str);

        return;
    }

    //Попытка авторизации клиента (проверка по БД)
    QString instructorName;
    QString traineeName;
    QByteArray arrayAnswer;

    if(pInstructorsAndTrainees->authorizationTrainee(clientAutorization.Login, clientAutorization.Password, "", ""))
    {//Авторизуется обучаемый

        client->getClient()->setLogin(clientAutorization.Login);
        emit sigUpdateListClients();

        //KAV redact
        instructorName = pInstructorsAndTrainees->getMainInstructorName();
        traineeName = pInstructorsAndTrainees->getNameTraineeByLogin(clientAutorization.Login);

        arrayAnswer = dataParser->xmlAnswer_authorization(true, instructorName, traineeName, "trainee");
    }
    else if(pInstructorsAndTrainees->authorizationInstructor(clientAutorization.Login, clientAutorization.Password))
    {//Авторизуется инструктор

        client->getClient()->setLogin(clientAutorization.Login);
        emit sigUpdateListClients();

        instructorName = pInstructorsAndTrainees->getNameInstructorByLogin(clientAutorization.Login);

        arrayAnswer = dataParser->xmlAnswer_authorization(true, instructorName, instructorName, "instructor");
    }
    else
    {//Никто не авторизовался
        arrayAnswer = dataParser->xmlAnswer_authorization(false, "", "", "");
    }
    client->sendXmlAnswer(arrayAnswer);

    QString str = QString(arrayAnswer);
    //logger->addTextToLogger("To Client: " + str);

    //Извещаем об изменениях в авторизации
    emit sigAuthChanged();
}

void ProcessingSystem::processingClientMessage(ClientHandler *client, ClientMessage clientMessage)
{
    QString peerAddress = client->getSocket()->peerAddress().toString();
    QString peerPort = QString::number(client->getSocket()->peerPort());

    QString str = "Msg From Client [" + peerAddress + ":" + peerPort + "] : " + clientMessage.Text;

    emit sigLogMessage(str);
    emit sigAddToMessanger(client->getClient()->getLogin(), clientMessage.Text);
}

void ProcessingSystem::processingClientNotify(ClientHandler *client, ClientNotify clientNotify)
{
    if(clientNotify.Code == "READY")
    {//Клиент готов принять задания
        client->getClient()->setReady(true);    //скорее всего функции будут внутри хэндлера

        //Отправляем пакет с заданиями для Обучаемого(клиента)

        client->getSocket()->flush();

        QStringList listTasks;
        //TODO KAV redact
        //listTasks = pInstructorsAndTrainees->getDbLMS()->getWhatItDoes(client->getClient()->getLogin());

        QByteArray arrayAnswer = dataParser->xmlAnswer_tasks(listTasks);
        client->sendXmlAnswer(arrayAnswer);

        QString str = QString(arrayAnswer);
        emit sigLogMessage("To Client: " + str);
    }
    else if(clientNotify.Code == "DISABLE")
    {
        client->sendDisable();
        //server->slotDisconnectClient(client->getClient()->getAddress(),client->getClient()->getPort());
    }
    else if(clientNotify.Code == "GETSERVERDATALIST")
    {
        client->sendHash();
    }
}



