#include "processingsystem.h"
#include "providerdblms.h"

#include <clienthandler.h>

ProcessingSystem::ProcessingSystem(ProviderDBLMS* providerDBLMS, UpdateController* updateController, QObject *parent):
    QObject(parent),
    updateController(nullptr),
    providerDBLMS(nullptr)
{
    this->providerDBLMS = providerDBLMS;
    this->updateController = updateController;
}

void ProcessingSystem::initialize(MultiThreadServer *server, DataParser *dataParser,
                                  CommonClientHandler *commonClientHandler,
                                  UpdateController *updateController,
                                  ChatSystem *chatSystem)
{
    this->commonClientServer = commonClientHandler;
    this->dataParser = dataParser;
    this->server = server;
    this->updateController = updateController;
    this->chatSystem = chatSystem;

    connect(this,&ProcessingSystem::sigListsInstructorsTraineesChanged,commonClientHandler, &CommonClientHandler::slot_ListsInstructorsTraineesChanged,Qt::AutoConnection);

    connect(this,&ProcessingSystem::sigStatusTasksAMMofTraineeChanged,commonClientHandler, &CommonClientHandler::slot_StatusTasksAMMofTraineeChanged,Qt::AutoConnection);
    connect(this,&ProcessingSystem::sigStatusTasksFIMofTraineeChanged,commonClientHandler, &CommonClientHandler::slot_StatusTasksFIMofTraineeChanged,Qt::AutoConnection);
    connect(this,&ProcessingSystem::sigUpdateListClients,server,&MultiThreadServer::updateClientList,Qt::AutoConnection);
    connect(this,&ProcessingSystem::sigSetData,updateController,&UpdateController::setDataInfo,Qt::AutoConnection);
}

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

        QString str = QString(arrayAnswer);
        Logger::instance().log("To Client: " + str);

        return;
    }

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


    if(providerDBLMS->authorizationInstructor(clientAutorization.Login, clientAutorization.Password))
    {//Авторизуется инструктор

        client->getClient()->setLogin(clientAutorization.Login);
        client->getClient()->setAccessType(UserType::INSTRUCTOR);
        client->getClient()->setTypeClient(clientAutorization.TypeClient);

        emit sigUpdateListClients();

        instructorName = providerDBLMS->getNameInstructorByLogin(clientAutorization.Login);
        clientID = providerDBLMS->getIdInstructorByLogin(clientAutorization.Login);
        client->getClient()->setId(QString::number(clientID));
        arrayAnswer = dataParser->ClientAnswer()->authorization(true, instructorName, instructorName, "instructor", clientAutorization.Login, clientID);
    }
    else if(clientAutorization.TypeClient != TypeClientAutorization::TYPE_GUI)
    {
        if(providerDBLMS->authorizationTrainee(clientAutorization.Login, clientAutorization.Password, "", ""))
        {//Авторизуется обучаемый

            client->getClient()->setLogin(clientAutorization.Login);
            client->getClient()->setAccessType(UserType::TRAINEE);
            emit sigUpdateListClients();

            //KAV redact
            instructorName = providerDBLMS->getMainInstructorName();
            traineeName = providerDBLMS->getNameTraineeByLogin(clientAutorization.Login);
            clientID = providerDBLMS->getIdTraineeByLogin(clientAutorization.Login);
            client->getClient()->setId(QString::number(clientID));
            arrayAnswer = dataParser->ClientAnswer()->authorization(true, instructorName, traineeName, "trainee", clientAutorization.Login, clientID);
        }
        else
        {//Никто не авторизовался
            arrayAnswer = dataParser->ClientAnswer()->authorization(false, "", "", "", "", 0);
        }
    }
    else
    {//Никто не авторизовался
        arrayAnswer = dataParser->ClientAnswer()->authorization(false, "", "", "", "", 0);
    }
    client->sendXmlAnswer(arrayAnswer);
    client->sendVersion();

    QString str = QString(arrayAnswer);
    //logger->addTextToLogger("To Client: " + str);
    //Извещаем об изменениях в авторизации
    emit sigListsInstructorsTraineesChanged();
}

void ProcessingSystem::processingClientDeAutorization(ClientHandler *client, ClientDeAutorization clientDeAutorization)
{
    if(server->getStateBlockAutorization() == blocked)
    {
        QByteArray arrayAnswer = dataParser->ClientAnswer()->notify(NOTIFY_SERVER_BLOCKED);
        client->sendXmlAnswer(arrayAnswer);

        QString str = QString(arrayAnswer);
        Logger::instance().log("To Client: " + str);

        return;
    }

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

    if(providerDBLMS->deAuthorizationTrainee(clientDeAutorization.Login))
    {//ДеАвторизуется обучаемый

        client->getClient()->setLogin("");
        client->getClient()->setAccessType(UserType::NONE);
        client->getClient()->setIsLoggedIn(false);
        emit sigUpdateListClients();

        arrayAnswer = dataParser->ClientAnswer()->deAuthorization(true, clientDeAutorization.Login);
    }
    else if(providerDBLMS->deAuthorizationInstructor(clientDeAutorization.Login))
    {//ДеАвторизуется инструктор

        client->getClient()->setLogin("");
        client->getClient()->setAccessType(UserType::NONE);
        client->getClient()->setIsLoggedIn(false);
        emit sigUpdateListClients();

        arrayAnswer = dataParser->ClientAnswer()->deAuthorization(true, clientDeAutorization.Login);
    }
    else
    {//Никто не ДеАвторизовался
        arrayAnswer = dataParser->ClientAnswer()->deAuthorization(false, "");
    }
    client->sendXmlAnswer(arrayAnswer);

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

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

//упращенная деавторизация при выключении сервера
void ProcessingSystem::processingClientDeAutorization(QString login)
{
    //Отмена авторизации в БД

    if(providerDBLMS->deAuthorizationTrainee(login))
    {//Деавторизовался обучаемый

    }
    else  if(providerDBLMS->deAuthorizationInstructor(login))
    {//Деавторизовался инструктор

    }
}

void ProcessingSystem::processingEntryUnityClient(ClientHandler *client)
{
    QString login = client->getClient()->getLogin();
    UserType userType = client->getClient()->getAccessType();

    if(userType == UserType::TRAINEE)
    {
        int id_trainee = providerDBLMS->getIdTraineeByLogin(login);
        providerDBLMS->entryTraineeOnSimulator(id_trainee);
    }
    else if(userType == UserType::INSTRUCTOR)
    {
        //Здесь пока ничего не происходит
    }
}

void ProcessingSystem::processingExitUnityClient(ClientHandler *client)
{
    QString login = client->getClient()->getLogin();
    UserType userType = client->getClient()->getAccessType();

    if(userType == UserType::TRAINEE)
    {
        int id_trainee = providerDBLMS->getIdTraineeByLogin(login);
        providerDBLMS->exitTraineeFromSimulator(id_trainee);
    }
    else if(userType == UserType::INSTRUCTOR)
    {
        //Здесь пока ничего не происходит
    }
}

void ProcessingSystem::processingClientQueryToDB(ClientHandler *client, ClientQueryToDB clientQueryToDB, int id, void* data)
{
    qDebug() << "ProcessingQueryThread " << QThread::currentThreadId();

    switch (clientQueryToDB.typeQuery)
    {
        case TypeQueryToDB::TYPE_QUERY_GET_ALL_LISTS:
        {
            QList<Instructor> listInstructors = providerDBLMS->GetListAllInstructors();
            QList<Trainee> listTrainees = providerDBLMS->GetListAllTrainees();
            QList<Group> listGroups = providerDBLMS->GetListAllGroups();

            QByteArray arrayAnswer;

            arrayAnswer = dataParser->DbAnswer()->listInstructors(true, &listInstructors);
            //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_DB__LIST_INSTRUCTORS);
            client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_DB__LIST_INSTRUCTORS);

            arrayAnswer = dataParser->DbAnswer()->listGroups(true, &listGroups);
            //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_DB__LIST_GROUPS);
            client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_DB__LIST_GROUPS);

            arrayAnswer = dataParser->DbAnswer()->listTrainees(true, &listTrainees);
            //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_DB__LIST_TRAINEES);
            client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_DB__LIST_TRAINEES);
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_NEW_INSTRUCTOR:
        {
            int id_new;
            id_new = providerDBLMS->newInstructor();
            if(id_new)
            {
                (*(Instructor*)data).setID(id_new);
                providerDBLMS->editInstructor(*(Instructor*)data);
            }
            emit sigListsInstructorsTraineesChanged();
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_DEL_INSTRUCTOR:
        {
            providerDBLMS->delInstructor(id);
            emit sigListsInstructorsTraineesChanged();
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_EDIT_INSTRUCTOR:
        {
            providerDBLMS->editInstructor(*(Instructor*)data);
            emit sigListsInstructorsTraineesChanged();
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_NEW_TRAINEE:
        {
            int id_new;
            id_new = providerDBLMS->newTrainee(id);
            if(id_new)
            {
                (*(Trainee*)data).setID(id_new);
                providerDBLMS->editTrainee(*(Trainee*)data);
            }
            emit sigListsInstructorsTraineesChanged();
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_DEL_TRAINEE:
        {
            providerDBLMS->delTrainee(id);
            emit sigListsInstructorsTraineesChanged();
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_EDIT_TRAINEE:
        {
            providerDBLMS->editTrainee(*(Trainee*)data);
            emit sigListsInstructorsTraineesChanged();
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_NEW_GROUP:
        {
            int id_new;
            id_new = providerDBLMS->newGroup();
            if(id_new)
            {
                (*(Group*)data).setID(id_new);
                providerDBLMS->editGroup(*(Group*)data);
            }
            emit sigListsInstructorsTraineesChanged();
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_DEL_GROUP:
        {
            providerDBLMS->delGroup(id);
            emit sigListsInstructorsTraineesChanged();
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_EDIT_GROUP:
        {
            providerDBLMS->editGroup(*(Group*)data);
            emit sigListsInstructorsTraineesChanged();
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_ASSIGN_TASK_AMM_TO_TRAINEE:
        {
            int  id_trainee = id;
            if(int id_new = providerDBLMS->newTaskAMM(*(TaskAmmFim*)data, id_trainee))
            {
                //Отправка списка задач AMM всем клиентам GUI
                //sendListTasksAMMofTraineetoClient(client, id_trainee);
                emit sigStatusTasksAMMofTraineeChanged(id_trainee);

                //Отправка списка задач AMM клиенту Юнити
                if(ClientHandler* clientUnity = getUnityClientById(id_trainee))
                {//Есть такой
                    //sendListTasksAMMofTraineetoClient(clientUnity, id_trainee);
                    QList<int> listID;
                    listID.append(id_new);
                    sendListTasksAMMofTraineeByIDtoClient(clientUnity, id_trainee, listID);
                }
            }
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_ASSIGN_TASK_FIM_TO_TRAINEE:
        {
            int  id_trainee = id;
            if(int id_new = providerDBLMS->newTaskFIM(*(TaskAmmFim*)data, id_trainee))
            {
                //Отправка списка задач FIM всем клиентам GUI
                //sendListTasksFIMofTraineetoClient(client, id_trainee);
                emit sigStatusTasksFIMofTraineeChanged(id_trainee);

                //Отправка списка задач FIM клиенту Юнити
                if(ClientHandler* clientUnity = getUnityClientById(id_trainee))
                {//Есть такой
                    //sendListTasksFIMofTraineetoClient(clientUnity, id_trainee);
                    QList<int> listID;
                    listID.append(id_new);
                    sendListTasksFIMofTraineeByIDtoClient(clientUnity, id_trainee, listID);
                }
            }
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_GET_TASKS_AMM_FOR_TRAINEE:
        {
            int  id_trainee = id;
            //Отправка списка задач AMM клиенту GUI
            sendListTasksAMMofTraineetoClient(client, id_trainee);
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_GET_TASKS_FIM_FOR_TRAINEE:
        {
            int  id_trainee = id;
            //Отправка списка задач FIM клиенту GUI
            sendListTasksFIMofTraineetoClient(client, id_trainee);
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_DEL_TASK_AMM_TO_TRAINEE:
        {
            int id_task = id;
            TaskAmmFim task = providerDBLMS->getTaskAMMbyID(id_task);

            if(int id_trainee = providerDBLMS->delTaskAMM(id_task))
            {
                task.status = "deleted";

                //Отправка списка задач AMM всем клиентам GUI
                //sendListTasksAMMofTraineetoClient(client, id_trainee);
                emit sigStatusTasksAMMofTraineeChanged(id_trainee);

                //Отправка списка задач AMM клиенту Юнити
                if(ClientHandler* clientUnity = getUnityClientById(id_trainee))
                {//Есть такой
                    //sendListTasksAMMofTraineetoClient(clientUnity, id_trainee);
                    sendTaskAMMToClient(clientUnity, id_trainee, task);
                }
            }
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_DEL_TASK_FIM_TO_TRAINEE:
        {
            int id_task = id;
            TaskAmmFim task = providerDBLMS->getTaskFIMbyID(id_task);

            if(int id_trainee = providerDBLMS->delTaskFIM(id))
            {
                task.status = "deleted";

                //Отправка списка задач FIM клиенту GUI
                //sendListTasksFIMofTraineetoClient(client, id_trainee);
                emit sigStatusTasksFIMofTraineeChanged(id_trainee);

                //Отправка списка задач FIM клиенту Юнити
                if(ClientHandler* clientUnity = getUnityClientById(id_trainee))
                {//Есть такой
                    //sendListTasksFIMofTraineetoClient(clientUnity, id_trainee);
                    sendTaskFIMToClient(clientUnity, id_trainee, task);
                }
            }            
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_SET_REPORT_TASK_AMM_TO_TRAINEE:
        {
            TaskAmmFim* task = (TaskAmmFim*)data;
            if(task->status == "completed")
                if( int id_trainee = providerDBLMS->changeStatusTaskAMM(task->getID(), "completed") )
                {

                }
            break;
        }
        case TypeQueryToDB::TYPE_QUERY_SET_REPORT_TASK_FIM_TO_TRAINEE:
        {
            TaskAmmFim* task = (TaskAmmFim*)data;
            if(task->status == "checkup")
                if(int id_report = providerDBLMS->replaceReportFIM(*task))
                {

                }
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_CHANGE_STATUS_REPORT_TASK_AMM_TO_TRAINEE:
        {
            QString* status = (QString*)data;
            if(int id_trainee = providerDBLMS->changeStatusTaskAMM(id, *status))
            {
                //Отправка списка задач AMM всем клиентам GUI
                //sendListTasksAMMofTraineetoClient(client, id_trainee);
                emit sigStatusTasksAMMofTraineeChanged(id_trainee);

                //Отправка списка задач AMM клиенту Юнити
                if(ClientHandler* clientUnity = getUnityClientById(id_trainee))
                {//Есть такой
                    //sendListTasksAMMofTraineetoClient(clientUnity, id_trainee);
                    QList<int> listID;
                    listID.append(id);
                    sendListTasksAMMofTraineeByIDtoClient(clientUnity, id_trainee, listID);
                }
            }
            break;
        }

        case TypeQueryToDB::TYPE_QUERY_CHANGE_STATUS_REPORT_TASK_FIM_TO_TRAINEE:
        {
            QString* status = (QString*)data;
            if(int id_trainee = providerDBLMS->changeStatusTaskFIM(id, *status))
            {
                //Отправка списка задач FIM всем клиентам GUI
                //sendListTasksFIMofTraineetoClient(client, id_trainee);
                emit sigStatusTasksFIMofTraineeChanged(id_trainee);

                //Отправка списка задач FIM клиенту Юнити
                if(ClientHandler* clientUnity = getUnityClientById(id_trainee))
                {//Есть такой
                    //sendListTasksFIMofTraineetoClient(clientUnity, id_trainee);
                    QList<int> listID;
                    listID.append(id);
                    sendListTasksFIMofTraineeByIDtoClient(clientUnity, id_trainee, listID);
                }
            }
            break;
        }

    case TypeQueryToDB::TYPE_QUERY_GET_CONTACT_LIST:
    {
        QList<ContactModel> entitylist;
        QList<Instructor> listInstructor = providerDBLMS->GetListAllInstructors();
        QList<Trainee> listTrainees = providerDBLMS->GetListAllTrainees();

        for (Instructor instructor : listInstructor)
        {
            ContactModel model = ContactModel(instructor);
            entitylist.append(model);
        }

        for (Trainee trainee : listTrainees)
        {
             ContactModel model = ContactModel(trainee);
             entitylist.append(model);
        }

        QByteArray arrayAnswer;

        arrayAnswer = dataParser->DbAnswer()->listContacts(true, &entitylist);

        client->sendFileBlockByteArray(arrayAnswer,PacketType::TYPE_BIGXML);
    }

    }
}

void ProcessingSystem::processingClientQueryTasksXML(ClientHandler *client, ClientQueryTasksXML clientQueryTasksXML)
{
    QByteArray arrayAnswer;

    QString nameFile = "";
    QString pathFile = "";
    if(clientQueryTasksXML.Type == "fim")
    {
        nameFile = tasksFIMfileName;
        pathFile = updateController->getPathAdditionalFile(nameFile);
        Logger::instance().log(pathFile);
        client->sendFileBlock(pathFile);
        client->sendPacketType(PacketType::TYPE_XMLANSWER_QUERY_TASKS_XML_FIM);
    }
    else if(clientQueryTasksXML.Type == "amm")
    {
        nameFile = tasksAMMfileName;
        pathFile = updateController->getPathAdditionalFile(nameFile);
        client->sendFileBlock(pathFile);
        client->sendPacketType(PacketType::TYPE_XMLANSWER_QUERY_TASKS_XML_AMM);
    }
}

void ProcessingSystem::processingSendMessage(ClientMessage clientMessage)
{
    chatSystem->sendMessage(clientMessage);
}

void ProcessingSystem::processingClientNotify(ClientHandler *client, ClientNotify clientNotify)
{
    if(clientNotify.Code == commandReadyClient)
    {//Клиент готов принять задания
        client->setReady(true);
        sendTaskListToUnity(client);
        client->getSocket()->flush();
    }
    else if(clientNotify.Code == commandStartTimerClient)
    {
        //Фиксируем время входа Юнити-клиента
        if (client->getClient()->getClientType() == TypeClientAutorization::TYPE_UNITY_CLIENT)
        {
            processingEntryUnityClient(client);
        }
    }
    else if(clientNotify.Code == commandDisableClient)
    {
        qDebug() << "processing thread: " << QThread::currentThreadId();

        //Фиксируем время выхода Юнити-клиента
        if (client->getClient()->getClientType() == TypeClientAutorization::TYPE_UNITY_CLIENT)
        {
            processingExitUnityClient(client);
        }

        client->sendDisable();
    }
    else if(clientNotify.Code == commandGetServerDataList)
    {
        client->sendHash();
    }
    else if(clientNotify.Code == commandCheckVersionList)
    {
        client->sendVersionList();
    }
    else if(clientNotify.Code == commandCanChangeVersion)
    {
        if (updateController->getCurrentVersion()->getIsChangeable())
        {
            client->sigSendNotify(commandChangable);
        }
        else
        {
            client->sigSendNotify(commandUnchangable);
        }

    }else if(clientNotify.Code == commandGetTasks)
    {
        sendTaskListToUnity(client);
    }
    else if (clientNotify.Code == commandeGetOfflineMessages)
    {
        chatSystem->sendOldMessages(client->getClient()->getId());
    }
}

void ProcessingSystem::setCurrentDataInfo(DataInfo *dataInfo)
{
    emit sigSetData(dataInfo);
}

void ProcessingSystem::sendListTasksAMMofTraineetoClient(ClientHandler *client, int id_trainee)
{
    QList<TaskAmmFim> listTasks = providerDBLMS->GetListTasksAMMofTrainee(id_trainee);
    QByteArray arrayAnswer = dataParser->DbAnswer()->listTasksAMMofTrainee(true, &listTasks, id_trainee, true);
    //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);
    client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);
}

void ProcessingSystem::sendListTasksFIMofTraineetoClient(ClientHandler *client, int id_trainee)
{
    QList<TaskAmmFim> listTasks = providerDBLMS->GetListTasksFIMofTrainee(id_trainee);
    QByteArray arrayAnswer = dataParser->DbAnswer()->listTasksFIMofTrainee(true, &listTasks, id_trainee, true);
    //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
    client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
}

void ProcessingSystem::sendListTasksAMMofTraineeByIDtoClient(ClientHandler *client, int id_trainee, QList<int> listID)
{
    QList<TaskAmmFim> listTasksNeed;
    QList<TaskAmmFim> listTasks = providerDBLMS->GetListTasksAMMofTrainee(id_trainee);

    for(int i = 0; i < listTasks.count(); i++)
    {
        TaskAmmFim task = listTasks.at(i);
        bool flNeed = false;
        for(int id : listID)
        {
            if(id == task.getID())
            {
                flNeed = true;
                break;
            }
        }
        if(flNeed)
            listTasksNeed.append(listTasks.at(i));
    }

    QByteArray arrayAnswer = dataParser->DbAnswer()->listTasksAMMofTrainee(true, &listTasksNeed, id_trainee, false);
    //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);
    client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);
}

void ProcessingSystem::sendListTasksFIMofTraineeByIDtoClient(ClientHandler *client, int id_trainee, QList<int> listID)
{
    QList<TaskAmmFim> listTasksNeed;
    QList<TaskAmmFim> listTasks = providerDBLMS->GetListTasksFIMofTrainee(id_trainee);

    for(int i = 0; i < listTasks.count(); i++)
    {
        TaskAmmFim task = listTasks.at(i);
        bool flNeed = false;
        for(int id : listID)
        {
            if(id == task.getID())
            {
                flNeed = true;
                break;
            }
        }
        if(flNeed)
            listTasksNeed.append(listTasks.at(i));
    }

    QByteArray arrayAnswer = dataParser->DbAnswer()->listTasksFIMofTrainee(true, &listTasksNeed, id_trainee, false);
    //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
    client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
}

void ProcessingSystem::sendTaskAMMToClient(ClientHandler *client, int id_trainee, TaskAmmFim task)
{
    QList<TaskAmmFim> listTasks;
    listTasks.append(task);

    QByteArray arrayAnswer = dataParser->DbAnswer()->listTasksAMMofTrainee(true, &listTasks, id_trainee, false);
    //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);
    client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);
}

void ProcessingSystem::sendTaskFIMToClient(ClientHandler *client, int id_trainee, TaskAmmFim task)
{
    QList<TaskAmmFim> listTasks;
    listTasks.append(task);

    QByteArray arrayAnswer = dataParser->DbAnswer()->listTasksFIMofTrainee(true, &listTasks, id_trainee, false);
    //client->sendXmlAnswer(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
    client->sendFileBlockByteArray(arrayAnswer, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
}

void ProcessingSystem::sendTaskListToUnity(ClientHandler *client)
{
    //Отправка списков задач клиенту Юнити
    if(client->getClient()->getClientType() == TypeClientAutorization::TYPE_UNITY_CLIENT)
    {
        QString login = client->getClient()->getLogin();
        int id_trainee = providerDBLMS->getIdTraineeByLogin(login);

        //AMM
        QList<TaskAmmFim> listTasksAMM = providerDBLMS->GetListTasksAMMofTrainee(id_trainee);
        QByteArray arrayAnswerTasksAMM = dataParser->DbAnswer()->listTasksAMMofTrainee(true, &listTasksAMM, id_trainee, true);
        client->sendFileBlockByteArray(arrayAnswerTasksAMM, PacketType::TYPE_XMLANSWER_QUERY_TASKS_AMM_OF_TRAINEE);

        //FIM
        QList<TaskAmmFim> listTasksFIM = providerDBLMS->GetListTasksFIMofTrainee(id_trainee);
        QByteArray arrayAnswerFIM = dataParser->DbAnswer()->listTasksFIMofTrainee(true, &listTasksFIM, id_trainee, true);
        client->sendFileBlockByteArray(arrayAnswerFIM, PacketType::TYPE_XMLANSWER_QUERY_TASKS_FIM_OF_TRAINEE);
    }
}

ClientHandler *ProcessingSystem::getUnityClientById(int id)
{
    QString login = providerDBLMS->getLoginTraineeById(id);

    //Проходим все открытые сокеты, ищем нужный
    foreach(int idSocket, server->getClientsMap()->keys())
    {
        ClientHandler *handler = server->getClientsMap()->value(idSocket);
        if(handler->getClient()->getLogin() == login)
        {
            if(handler->getClient()->getClientType() == TypeClientAutorization::TYPE_UNITY_CLIENT)
            {
                return handler;
            }
        }
    }
    return nullptr;
}



