#include "Core/recognizesystem.h"
#include <QThread>
#include <QDir>
#include <QDomDocument>
#include <QMessageBox>
#include "instructor.h"
#include "tasksAmmFim.h"
#include "timingoftrainee.h"


RecognizeSystem::RecognizeSystem(QObject *parent):
    QObject(parent)
{
    packetType = PacketType::TYPE_NONE;
    filePath.clear();
    fileSize = 0;
    message.clear();
    sizeReceiveData = 0;
    tmpBlock.clear();
    countSend = 0;
    folderList = new QList<QString>;
}

RecognizeSystem::~RecognizeSystem()
{

}

void RecognizeSystem::initialize(DataParser *dataParser/*,MainWindow *mainWindow*/)
{
    this->dataParser = dataParser;
    //this->mainWindow = mainWindow;
    connect(this,&RecognizeSystem::sigAuth,dataParser,&DataParser::createAuthData);
}

void RecognizeSystem::recognize(QTcpSocket *socket)
{
    qDebug() << "RecognizeThreadId " << QThread::currentThreadId();

    QDataStream stream(socket);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);

    while(socket->bytesAvailable())
    {

      if (socket->state() != QTcpSocket::ConnectedState) return;

        if(packetType == PacketType::TYPE_NONE){    //определение первичного пакета

            stream.startTransaction();
            stream >> packetType;

            if(!stream.commitTransaction()){
                emit sigSendDebugLog(Tools::getTime() + " CLIENT: packetType - FAIL commitTransaction");

                if(socket->waitForReadyRead(TCP_READ_TIMEOUT)){
                    emit sigSendDebugLog("ERROR: PACKET TYPE READ TIMEOUT");
                    return;
                }
                continue;

            }

            //qDebug() << Tools::GetTime() << "CLIENT: type: " << packetType;
        }

        if(packetType == PacketType::TYPE_FOLDER){  //создание папок
            stream.startTransaction();
            stream >> filePath;

            if(!stream.commitTransaction()){
                continue;
            }

            filePath = Tools::createFullPath(filePath);

            QDir dir(filePath);
            if(!dir.exists()){
                if(dir.mkpath(filePath)){
                    qDebug() << "Dir Created";
                }
            }

            packetType = PacketType::TYPE_NONE;
            emit sigUpdateBytesAvailable();
            continue;
        }

        if(packetType == PacketType::TYPE_FILE)     //загрузка файлов
        {
            //ПОЛУЧЕНИЕ ПУТИ
            //ПОЛУЧЕНИЕ РАЗМЕРА ФАЙЛА
            forever
            {
                stream.startTransaction();
                stream >> filePath;
                stream >> fileSize;

                if(!stream.commitTransaction()){
                    emit sigSendDebugLog(Tools::getTime() + "CLIENT: filePath, fileSize - FAIL commitTransaction");

                    if (!socket->waitForReadyRead(TCP_READ_TIMEOUT)) {
                        emit sigSendDebugLog(Tools::getTime() + "CLIENT: ERROR! readyRead timeout - filePath, fileSize!!!");
                        return;
                    }
                    continue;

                }

                filePath = Tools::createFullPath(filePath);

                emit sigSendDebugLog("CLIENT: filesize: " + QString::number(fileSize));
                emit sigSendDebugLog("CLIENT: filePath: " + filePath);

                socket->waitForReadyRead(100);
                break;
            }


            //ПОЛУЧЕНИЕ САМОГО ФАЙЛА
            emit sigSendDebugLog(Tools::getTime() + "AfterRead size and path BytesAvailable: " + socket->bytesAvailable());

            //УКАЗАНИЕ ПУТИ ФАЙЛА
            QFile file(filePath);

            if (file.exists())
            {
                file.remove();  //удаление файла, если он уже есть, но необходимо обновить
                emit sigSendDebugLog(Tools::getTime() + "Delete exist file: " + filePath);
                socket->waitForReadyRead(100);
            }



            file.open(QFile::Append);

            forever
            {
                stream.startTransaction();
                stream >> tmpBlock;

                if(!stream.commitTransaction()){

                    if(socket->state() == QAbstractSocket::UnconnectedState){
                        emit sigSocketDisabled();
                        return;
                    }
                    if(socket->waitForReadyRead(TCP_READ_TIMEOUT)){
                        continue;
                    }

                    continue;
                }

                quint64 toFile = file.write(tmpBlock);
                emit sigSendDebugLog(Tools::getTime() + "CLIENT: toFile :" + toFile);

                sizeReceiveData += toFile;
                countSend++;

                tmpBlock.clear();

                if(sizeReceiveData == fileSize){
                    emit sigSendDebugLog(Tools::getTime() + "FINAL Count send: " + QString::number(countSend));
                    emit sigSendDebugLog(Tools::getTime() + "FINAL Size received: " + QString::number(sizeReceiveData));
                    emit sigSendDebugLog(Tools::getTime() + "FINAL File size" + QString::number(fileSize));
                    emit sigUpdateBytesAvailable();
                    break;
                }
            }

            file.close();
            emit sigSendDebugLog(Tools::getTime() + "File loaded");

            //ОЧИСТКА ПОСЛЕ ПЕРЕДАЧИ

            filePath.clear();
            fileSize = 0;
            tmpBlock.clear();
            sizeReceiveData = 0;
            countSend = 0;
        }

        if(packetType == PacketType::TYPE_DELETE)   //удаление лишних файлов (рекурсивно удаляет все содежимое)
        {
            stream.startTransaction();
            stream >> filePath;

            if(!stream.commitTransaction()){
                continue;
            }

            filePath = Tools::createFullPath(filePath);

            QFileInfo fileInfo(filePath);


            if(fileInfo.exists())
            {
                if(fileInfo.isFile())
                {
                    QFile file(filePath);
                    file.remove();
                }

                if(fileInfo.isDir()){
                    QDir dir(filePath);
                    dir.removeRecursively();
                }

                qDebug() << Tools::getTime() << "Deleted: " << filePath;
            }

            packetType = PacketType::TYPE_NONE;
            continue;

        }

        if(packetType ==PacketType::TYPE_FINISH){   //для повторного создания хэша после загрузки
            //updateController->calculateCommonHash();
            emit sigLoadComplete();
            packetType = PacketType::TYPE_NONE;
        }

        if(packetType == PacketType::TYPE_NEEDUPDATE){  //нужно обновление

            bool flag = false;
            quint64 size = 0;
            quint64 fileCount = 0;

            stream.startTransaction();
            stream >> flag;
            stream >> size;
            stream >> fileCount;

            if(!stream.commitTransaction()){
                continue;
            }

            emit sigNeedUpdate(flag,size,fileCount);
            packetType = PacketType::TYPE_NONE;
        }

        if(packetType == PacketType::TYPE_XMLANSWER){   //ответы формата XML
            QByteArray array;
            stream.startTransaction();
            stream >> array;

            if(!stream.commitTransaction()){
                continue;
            }

            xmlParser(array);

            packetType = PacketType::TYPE_NONE;
        }


        if(packetType == PacketType::BUSY)
        {
            emit sigAnimationActivated(true);
        }

        if(packetType == PacketType::FREE)
        {
            emit sigAnimationActivated(false);
        }

        if(packetType == PacketType::HASH_READY)
        {
            emit sigHashReady();
        }

        //xml-ответы на запросы к БД
        switch(packetType)
        {
        case TYPE_XMLANSWER_QUERY_DB__LIST_INSTRUCTORS:
        case TYPE_XMLANSWER_QUERY_DB__LIST_GROUPS:
        case TYPE_XMLANSWER_QUERY_DB__LIST_TRAINEES:
        case TYPE_XMLANSWER_QUERY_DB__LIST_COMPUTERS:
        case TYPE_XMLANSWER_QUERY_DB__LIST_CLASSROOMS:
        case TYPE_XMLANSWER_QUERY_TASKS_AMM_FOR_TRAINEE:
        case TYPE_XMLANSWER_QUERY_TASKS_FIM_FOR_TRAINEE:
            {
                //ПОЛУЧЕНИЕ РАЗМЕРА ФАЙЛА
                forever
                {
                    stream.startTransaction();
                    stream >> fileSize;

                    if(!stream.commitTransaction()){
                        emit sigSendDebugLog(Tools::getTime() + "CLIENT: fileSize - FAIL commitTransaction");

                        if (!socket->waitForReadyRead(TCP_READ_TIMEOUT)) {
                            emit sigSendDebugLog(Tools::getTime() + "CLIENT: ERROR! readyRead timeout - fileSize!!!");
                            return;
                        }
                        continue;

                    }

                    emit sigSendDebugLog("CLIENT: filesize: " + QString::number(fileSize));

                    socket->waitForReadyRead(100);
                    break;
                }


                //ПОЛУЧЕНИЕ САМОГО ФАЙЛА
                emit sigSendDebugLog(Tools::getTime() + "AfterRead size and path BytesAvailable: " + socket->bytesAvailable());

                QByteArray array;

                forever
                {
                    stream.startTransaction();
                    stream >> tmpBlock;

                    if(!stream.commitTransaction()){

                        if(socket->state() == QAbstractSocket::UnconnectedState){
                            emit sigSocketDisabled();
                            return;
                        }
                        if(socket->waitForReadyRead(TCP_READ_TIMEOUT)){
                            continue;
                        }

                        continue;
                    }

                    array.append(tmpBlock);

                    emit sigSendDebugLog(Tools::getTime() + "CLIENT: toFile :" + array.size());

                    sizeReceiveData += array.size();
                    countSend++;

                    tmpBlock.clear();

                    if(sizeReceiveData == fileSize){
                        emit sigSendDebugLog(Tools::getTime() + "FINAL Count send: " + QString::number(countSend));
                        emit sigSendDebugLog(Tools::getTime() + "FINAL Size received: " + QString::number(sizeReceiveData));
                        emit sigSendDebugLog(Tools::getTime() + "FINAL File size" + QString::number(fileSize));
                        emit sigUpdateBytesAvailable();
                        break;
                    }
                }

                emit sigSendDebugLog(Tools::getTime() + "File loaded");

                //ОЧИСТКА ПОСЛЕ ПЕРЕДАЧИ
                fileSize = 0;
                tmpBlock.clear();
                sizeReceiveData = 0;
                countSend = 0;

                xmlParserQueryToDB(packetType, array);

                packetType = PacketType::TYPE_NONE;



                /*
                QByteArray array;
                stream.startTransaction();
                stream >> array;

                if(!stream.commitTransaction())
                    continue;

                xmlParserQueryToDB(packetType, array);

                packetType = PacketType::TYPE_NONE;
                */
            }
            break;
        };

        //xml-ответы на запросы AdditionalFiles (сигнал о чтении ранее принятого)
        if(packetType == PacketType::TYPE_XMLANSWER_QUERY_TASKS_XML_FIM ||
                packetType == PacketType::TYPE_XMLANSWER_QUERY_TASKS_XML_AMM)
        {
            QByteArray array;            
            QString xmlFileName = "";

            if(packetType == PacketType::TYPE_XMLANSWER_QUERY_TASKS_XML_FIM)
                xmlFileName = "./" + additionalFilesFolderName + "/tasksFIM.xml";
            else
                xmlFileName = "./" + additionalFilesFolderName + "/docs.xml"; //"/tasksAMM.xml";

            QFile xmlInFile(xmlFileName);
            if (!xmlInFile.open(QFile::ReadOnly | QFile::Text))
            {
                QMessageBox::critical(nullptr, tr("Attention!"), tr("The file could not be opened ") + xmlFileName);
                return;
            }
            else
            {
                array = xmlInFile.readAll();
                xmlInFile.close();
            }

            xmlParserQueryTasksXML(packetType, array);

            packetType = PacketType::TYPE_NONE;
        }

        packetType = PacketType::TYPE_NONE;
    }
}

void RecognizeSystem::xmlParser(QByteArray array)
{
    QXmlStreamReader xmlReader(array);

    xmlReader.readNext();
    QString name = xmlReader.name().toString();

    while(!xmlReader.atEnd())
    {
        name = xmlReader.name().toString();

        if(!xmlReader.isStartElement()) {
            xmlReader.readNext();
            continue;
        }

        if(xmlReader.name() == "ServerNotify")
        {
            foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
            {
                QString name = attr.name().toString();
                QString value = attr.value().toString();

                if(name == "Code")
                {
                    if (value == "END")
                    {
                        emit sigSocketDisabled();
                    }

                    if(value == "BLOCKED")
                    {
                        emit sigServerBlocked();
                    }

                    if(value == "HASHSENDCOMPLETE")
                    {
                        emit sigStartCompare();
                    }

                    if (value == "BASEDELETETRY")
                    {
                        emit sigNotify(tr("You cannot delete the basic version!"));
                    }

                    if (value == "TRYACTIVEDELETE")
                    {
                        emit sigNotify(tr("You cannot delete the active version"));
                    }

                    if (value == "DUPLICATEVERNAME")
                    {
                        emit sigNotify(tr("This name already exists"));
                    }
                }
            }
        }

        if(xmlReader.name() == "ServerAuthorization"){

            ServerAuthorization *serverAuth = new ServerAuthorization;

            foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
            {
                QString name = attr.name().toString();
                QString value = attr.value().toString();

                if (name == "Result"){
                    serverAuth->Result = value == "true" ? true : false;
                }

                if (name == "InstructorName"){
                    serverAuth->InstructorName = value;
                }

                if (name == "ClientName"){
                    serverAuth->ClientName = value;
                }

                if (name == "AccessType"){
                    serverAuth->AccessType = value;
                    checkAccessType(value);
                }

                if (name == "Login"){
                    serverAuth->Login = value;
                }

                if (name == "id_client")
                {
                    serverAuth->Id = value;
                }
            }

            emit sigAuth(serverAuth);
        }

        if(xmlReader.name() == "ClientMessage"){

            ClientMessage *clientMessage = new ClientMessage;

            foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
            {
                QString name = attr.name().toString();
                QString value = attr.value().toString();

                if (name == "From"){
                    clientMessage->fromId = value;
                }

                if (name == "To"){
                    clientMessage->toId = value;
                }

                if (name == "Text"){
                    clientMessage->Text = value;
                }
            }

            emit signal_ReceiveMessage(*clientMessage);
        }

        if(xmlReader.name() == "ServerDeAuthorization"){

            ServerDeAuthorization *serverDeAuth = new ServerDeAuthorization;

            foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
            {
                QString name = attr.name().toString();
                QString value = attr.value().toString();

                if (name == "Result"){
                    serverDeAuth->Result = value == "true" ? true : false;
                }

                if (name == "Login"){
                    serverDeAuth->Login = value;
                }
            }

            emit sigDeAuth(serverDeAuth);

        }


        if(xmlReader.name() == "VersionList")
        {
            QList<StreamingVersionData*> *serverStreamingVersionDataList = new QList<StreamingVersionData*>;
            xmlReader.readNext();

            while (!xmlReader.atEnd())
            {
                if(xmlReader.isStartElement())
                {
                    if(xmlReader.name() == "VersionData")
                    {
                        StreamingVersionData *data = new StreamingVersionData;

                        foreach(const QXmlStreamAttribute &attr,xmlReader.attributes())
                        {
                            QString name = attr.name().toString();
                            QString value = attr.value().toString();

                            if(name == "Version")
                                data->setName(value);
                            else if(name == "Created")
                                data->setCreateData(QDateTime::fromString(value));
                            else if(name == "isChangeable")
                                data->setIsChangeable(value.toInt());
                            else if(name == "author")
                                data->setAuthor(value);

                        }

                        serverStreamingVersionDataList->append(data);
                    }
                }

                xmlReader.readNext();
            }

            emit sigShowServerDataList(serverStreamingVersionDataList);
        }

        if(xmlReader.name() == "VersionData")
        {
            StreamingVersionData *serverVersion = new StreamingVersionData;
            foreach(const QXmlStreamAttribute &attr,xmlReader.attributes())
            {
                QString name = attr.name().toString();
                QString value = attr.value().toString();

                if (name == "Version")
                {
                    serverVersion->setName(value);
                }

                if (name == "Created")
                {
                    serverVersion->setCreateData(QDateTime::fromString(value));
                }

                if (name == "isChangeable")
                {
                    serverVersion->setIsChangeable(value.toInt());
                }

            }

            emit sigSetVersion(serverVersion);
        }

        xmlReader.readNext();
    }
}

void RecognizeSystem::xmlParserQueryToDB(PacketType packetType, QByteArray array)
{
    QDomDocument commonDOM;
    commonDOM.setContent(array);

    switch(packetType)
    {
        case TYPE_XMLANSWER_QUERY_DB__LIST_INSTRUCTORS:
        {
            QList<Instructor> listInstructors;
            QDomNode listNode = commonDOM.namedItem("ListInstructors");

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {
                QDomNode instructorNode = listNode.childNodes().at(i);
                if(instructorNode.nodeName() == "Instructor")
                {//Инструктор
                    Instructor instructor;
                    instructor.setID(instructorNode.toElement().attribute("instructor_id").toInt());
                    instructor.setName(instructorNode.toElement().attribute("name"));
                    instructor.setLogin(instructorNode.toElement().attribute("login"));
                    instructor.setPassword(instructorNode.toElement().attribute("password"));
                    instructor.setIsAdmin(instructorNode.toElement().attribute("is_admin").toInt());
                    instructor.setArchived(instructorNode.toElement().attribute("archived").toInt());
                    instructor.setLoggedIn(instructorNode.toElement().attribute("logged_in").toInt());

                    listInstructors.append(instructor);
                }
            }
            emit sigAnswerQueryToDB_ListInstructors(listInstructors);
        }
        break;
        case TYPE_XMLANSWER_QUERY_DB__LIST_GROUPS:
        {
            QList<Group> listGroups;
            QDomNode listNode = commonDOM.namedItem("ListGroups");

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {
                QDomNode groupNode = listNode.childNodes().at(i);
                if(groupNode.nodeName() == "Group")
                {//Группа
                    Group group;
                    group.setID(groupNode.toElement().attribute("group_id").toInt());
                    group.setName(groupNode.toElement().attribute("name"));

                    listGroups.append(group);
                }
            }
            emit sigAnswerQueryToDB_ListGroups(listGroups);
        }
        break;
        case TYPE_XMLANSWER_QUERY_DB__LIST_TRAINEES:
        {
            QList<Trainee> listTrainees;
            QDomNode listNode = commonDOM.namedItem("ListTrainees");

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {
                QDomNode traineeNode = listNode.childNodes().at(i);
                if(traineeNode.nodeName() == "Trainee")
                {//Обучаемый
                    Trainee trainee;
                    trainee.setID(traineeNode.toElement().attribute("trainee_id").toInt());
                    trainee.setName(traineeNode.toElement().attribute("name"));
                    trainee.setLogin(traineeNode.toElement().attribute("login"));
                    trainee.setPassword(traineeNode.toElement().attribute("password"));
                    trainee.setArchived(traineeNode.toElement().attribute("archived").toInt());
                    trainee.setLoggedIn(traineeNode.toElement().attribute("logged_in").toInt());
                    Group group(traineeNode.toElement().attribute("group_trainee").toInt(), "");
                    trainee.setGroup(group);
                    //trainee.setComputer()
                    //trainee.setTasks()


                    //Тайминг
                    QDomNode timingNode = traineeNode.firstChildElement("timing");

                    TimingOfTrainee timing(trainee.getID());
                    timing.setEntryTimeS(timingNode.toElement().attribute("entryTime"));
                    timing.setExitTimeS(timingNode.toElement().attribute("exitTime"));
                    timing.setOperatingTimeS(timingNode.toElement().attribute("operatingTime"));

                    trainee.setTiming(timing);


                    listTrainees.append(trainee);
                }
            }
            emit sigAnswerQueryToDB_ListTrainees(listTrainees);
        }
        break;
        case TYPE_XMLANSWER_QUERY_DB__LIST_COMPUTERS:
        {
            QList<Computer> listComputers;
            QDomNode listNode = commonDOM.namedItem("ListComputers");

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {
                QDomNode computerNode = listNode.childNodes().at(i);
                if(computerNode.nodeName() == "Computer")
                {//Компьютер
                    Computer computer;
                    computer.setID(computerNode.toElement().attribute("computer_id").toInt());
                    computer.setName(computerNode.toElement().attribute("name"));
                    computer.setIpAddress(computerNode.toElement().attribute("ip_address"));
                    //computer.setClassroom

                    listComputers.append(computer);
                }
            }
            emit sigAnswerQueryToDB_ListComputers(listComputers);
        }
        break;
        case TYPE_XMLANSWER_QUERY_DB__LIST_CLASSROOMS:
        {
            QList<Classroom> listClassrooms;
            QDomNode listNode = commonDOM.namedItem("ListClassrooms");

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {
                QDomNode classroomNode = listNode.childNodes().at(i);
                if(classroomNode.nodeName() == "Classroom")
                {//Класс
                    Classroom classroom;
                    classroom.setID(classroomNode.toElement().attribute("classroom_id").toInt());
                    classroom.setName(classroomNode.toElement().attribute("name"));

                    listClassrooms.append(classroom);
                }
            }
            emit sigAnswerQueryToDB_ListClassrooms(listClassrooms);
        }
        break;
        case TYPE_XMLANSWER_QUERY_TASKS_AMM_FOR_TRAINEE:
        {
            QList<TaskAmmFim> listTasks;
            int trainee_id = 0;
            QDomNode listNode = commonDOM.namedItem("ListTasksAMM");
            trainee_id = listNode.toElement().attribute("trainee_id").toInt();

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {
                QDomNode taskNode = listNode.childNodes().at(i);
                if(taskNode.nodeName() == "taskAMM")
                {//Задача
                    TaskAmmFim task;
                    task.setID(taskNode.toElement().attribute("task_id").toInt());
                    task.ammProcedure.title = taskNode.toElement().attribute("title");
                    task.ammProcedure.dmCode = taskNode.toElement().attribute("dmCode");
                    task.status = taskNode.toElement().attribute("status");

                    listTasks.append(task);
                }
            }
            emit sigAnswerQueryToDB_ListTasksAMMforTrainee(listTasks, trainee_id);
        }
        break;
        case TYPE_XMLANSWER_QUERY_TASKS_FIM_FOR_TRAINEE:
        {
            QList<TaskAmmFim> listTasks;
            int trainee_id = 0;
            QDomNode listNode = commonDOM.namedItem("ListTasksFIM");
            trainee_id = listNode.toElement().attribute("trainee_id").toInt();

            for(int i = 0; i < listNode.childNodes().count(); i++)
            {//Задачи
                QDomNode taskNode = listNode.childNodes().at(i);
                if(taskNode.nodeName() == "taskFIM")
                {
                    TaskAmmFim task;
                    task.setID(taskNode.toElement().attribute("task_id").toInt());
                    task.title = taskNode.toElement().attribute("title");
                    task.status = taskNode.toElement().attribute("status");

                    for(int j = 0; j < taskNode.childNodes().count(); j++)
                    {
                        QDomNode malfOrReportNode = taskNode.childNodes().at(j);
                        if(malfOrReportNode.nodeName() == "malfunction")
                        {//Неисправность
                            Malfunction malfunction;
                            malfunction.num = malfOrReportNode.toElement().attribute("num");
                            malfunction.dmCode = malfOrReportNode.toElement().attribute("dmCode");
                            malfunction.description = malfOrReportNode.toElement().attribute("description");

                            for(int s = 0; s < malfOrReportNode.childNodes().count(); s++)
                            {
                                QDomNode signNode = malfOrReportNode.childNodes().at(s);
                                if(signNode.nodeName() == "malfunctionSign")
                                {
                                    MalfunctionSign sign;
                                    sign.type = signNode.toElement().attribute("type").toInt();
                                    sign.description = signNode.toElement().attribute("description");

                                    malfunction.malfunctionSigns.append(sign);
                                }
                            }

                            task.malfunctionList.append(malfunction);
                        }
                        else
                            if(malfOrReportNode.nodeName() == "report")
                            {//Отчет
                                FIMReport report;
                                report.id = malfOrReportNode.toElement().attribute("report_id").toInt();

                                for(int k = 0; k < malfOrReportNode.childNodes().count(); k++)
                                {
                                    QDomNode reportItemNode = malfOrReportNode.childNodes().at(k);
                                    if(reportItemNode.nodeName() == "reportItem")
                                    {
                                        FIMReportItem reportItem;
                                        reportItem.id = reportItemNode.toElement().attribute("item_id").toInt();
                                        reportItem.text = reportItemNode.toElement().attribute("text");

                                        if(reportItemNode.childNodes().count())
                                        {
                                            QDomNode procedureIDNode = reportItemNode.childNodes().at(0);
                                            reportItem.procedure.doc = procedureIDNode.toElement().attribute("doc");
                                            reportItem.procedure.title = procedureIDNode.toElement().attribute("title");
                                            reportItem.procedure.dmCode = procedureIDNode.toElement().attribute("dmCode");
                                            reportItem.procedure.result = procedureIDNode.toElement().attribute("result");
                                        }

                                        report.itemList.append(reportItem);
                                    }
                                }

                                task.report = report;
                            }
                    }

                    listTasks.append(task);
                }
            }
            emit sigAnswerQueryToDB_ListTasksFIMforTrainee(listTasks, trainee_id);
        }
        break;
    };
}

void RecognizeSystem::xmlParserQueryTasksXML(PacketType packetType, QByteArray array)
{
    if(packetType == TYPE_XMLANSWER_QUERY_TASKS_XML_FIM)
    {
        emit sigAnswerQueryTasksXML_FIM(array);
    }
    else if(packetType == TYPE_XMLANSWER_QUERY_TASKS_XML_AMM)
    {
        emit sigAnswerQueryTasksXML_AMM(array);
    }
}

void RecognizeSystem::checkAccessType(QString type)
{
    if(type == "instructor")
    {
        //mainWindow->callUpdateList();
    }
}
