#include <QDomDocument>
#include <QFile>
#include <QMessageBox>
#include <QTreeWidget>
#include <QThread>
#include "fimtaskswidget.h"
#include "ui_fimtaskswidget.h"
#include "tasksAmmFim.h"

FIMtasksWidget::FIMtasksWidget(ConnectorToServer* connectorToServer, TypeList type, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FIMtasksWidget),
    connectorToServer(connectorToServer),
    treeWidget(nullptr),
    type(type),
    userName(""),
    loginTraineeSelected("")
{
    ui->setupUi(this);

    qDebug() << "FIMtasksWidget init thread ID " << QThread::currentThreadId();

    treeWidget = new QTreeWidget();
    ui->horizontalLayout_1->addWidget(treeWidget);

    connect(treeWidget, &QTreeWidget::currentItemChanged, this, &FIMtasksWidget::on_treeWidget_currentItemChanged);

    preparationTreeWidget();

    ui->btnAssignTaskToTrainee->setEnabled(false);
    ui->btnUpdateTasks->setVisible(false);

    if(type == TypeList::listForTrainee)
    {
        ui->btnAssignTaskToTrainee->setVisible(false);
        ui->label->setVisible(false);
        ui->editCode->setVisible(false);
    }
}

FIMtasksWidget::~FIMtasksWidget()
{

    deleteAllTaskAmmFim();
    delete ui;
}

void FIMtasksWidget::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    if(current == nullptr)
        return;

    QString code = "";

    QTreeWidgetItem *treeItemParent = current->parent();
    if(treeItemParent == nullptr)
    {//Выбрана задача
        int id = current->text(ColumnsTree::clmn_ID).toInt();

        TaskAmmFim* task = getTaskByID(id);

        code = task->title;

        ui->btnAssignTaskToTrainee->setEnabled(true);
    }
    else
        ui->btnAssignTaskToTrainee->setEnabled(false);

    ui->editCode->setText(code);
}

void FIMtasksWidget::loadFIMtasksFromXML(QByteArray array)
{
    deleteAllTaskAmmFim();

    QDomDocument docTasksDOM;

    docTasksDOM.setContent(array);

    QDomElement RRJTasksElement = docTasksDOM.firstChildElement("RRJTasks");
    if(RRJTasksElement.isNull())
        return;

    QDomElement taskElement = RRJTasksElement.firstChildElement();
    if(taskElement.isNull())
        return;

    do
    {/*task*/
        QString name = taskElement.nodeName();
        QDomNamedNodeMap nodeMap = taskElement.attributes();

        if(name == "task")
        {
            TaskAmmFim* task = nullptr;
            task = new TaskAmmFim();

            task->initialize(/*nodeMap.namedItem("id").nodeValue().toInt()*/ TaskAmmFim::lastID++,
                             nodeMap.namedItem("type").nodeValue(),
                             nodeMap.namedItem("title").nodeValue(),
                             nodeMap.namedItem("status").nodeValue(),
                             nodeMap.namedItem("created").nodeValue(),
                             nodeMap.namedItem("changed").nodeValue());

            QDomElement malfunctionElement = taskElement.firstChildElement();
            if(!malfunctionElement.isNull())
            {
                do
                {/*malfunction*/
                    QString name = malfunctionElement.nodeName();
                    QDomNamedNodeMap nodeMap = malfunctionElement.attributes();

                    if(name == "malfunction")
                    {
                        Malfunction malfunction;

                        malfunction.initialize(nodeMap.namedItem("dmCode").nodeValue(),
                                               nodeMap.namedItem("num").nodeValue(),
                                               nodeMap.namedItem("description").nodeValue());

                        QDomElement signElement = malfunctionElement.firstChildElement();
                        if(!signElement.isNull())
                        {
                            do
                            {/*malfunctionSign*/
                                QString name = signElement.nodeName();
                                QDomNamedNodeMap nodeMap = signElement.attributes();

                                if(name == "malfunctionSign")
                                {
                                    MalfunctionSign sign;

                                    sign.initialize(nodeMap.namedItem("type").nodeValue().toInt(),
                                                    nodeMap.namedItem("description").nodeValue());

                                    malfunction.addMalfunctionSign(sign);
                                }

                            }while(! (signElement = signElement.nextSiblingElement()).isNull());
                        }
                        task->addMalfunction(malfunction);
                    }
                }while(! (malfunctionElement = malfunctionElement.nextSiblingElement()).isNull());
            }
            listTaskAmmFim.append(task);
        }
    }while (! (taskElement = taskElement.nextSiblingElement()).isNull());

    return;
}

void FIMtasksWidget::fillTree()
{
    for(int i = 0; i < listTaskAmmFim.count(); i++)
    {/*Задачи*/
        TaskAmmFim* task = listTaskAmmFim.at(i);

        QTreeWidgetItem* itemTask = new QTreeWidgetItem();

        itemTask->setText(0, task->title);
        itemTask->setText(1, QString::number(task->id));
        //itemTask->setFlags(itemTask->flags() | Qt::ItemIsUserCheckable);
        //itemTask->setCheckState(0, Qt::Checked);
        itemTask->setIcon(0, QIcon(":/resources/icons/procedure.png"));

        treeWidget->addTopLevelItem(itemTask);

        for (int j = 0; j < task->malfunctionList.count(); j++)
        {/*Неисправности*/
            Malfunction malfunction = task->malfunctionList.at(j);

            QTreeWidgetItem* itemMalfunction = new QTreeWidgetItem();

            itemMalfunction->setText(0, malfunction.description);
            itemMalfunction->setFlags(itemMalfunction->flags() | Qt::ItemIsUserCheckable);
            itemMalfunction->setCheckState(0, Qt::Checked);
            itemMalfunction->setIcon(0, QIcon(":/resources/icons/malfunction.png"));

            itemTask->addChild(itemMalfunction);

            for (int k = 0; k < malfunction.malfunctionSigns.count(); k++)
            {/*Сигнализация*/
                MalfunctionSign sign = malfunction.malfunctionSigns.at(k);

                QTreeWidgetItem* itemSign = new QTreeWidgetItem();

                itemSign->setText(0, sign.description);
                //itemSign->setFlags(itemSign->flags() | Qt::ItemIsUserCheckable);
                //itemSign->setCheckState(0, Qt::Checked);
                itemSign->setIcon(0, QIcon(":/resources/icons/sign.png"));

                itemMalfunction->addChild(itemSign);
            }
        }
    }
}

void FIMtasksWidget::preparationTreeWidget()
{
    treeWidget->setColumnCount(2);

    reSetHeadTreeWidget();

    treeWidget->setColumnWidth(ColumnsTree::clmn_ID, 20);
    treeWidget->setColumnWidth(ColumnsTree::clmn_Title, 500);

    //treeWidget->setColumnHidden(ColumnsTree::clmn_ID, true);
}

void FIMtasksWidget::reSetHeadTreeWidget()
{
    QStringList listHeaders = {tr("Title"), tr("ID")};
    treeWidget->setHeaderLabels(listHeaders);
}

void FIMtasksWidget::slot_NeedUpdateUI()
{
    qDebug() << "FIMtasksWidget::slot_NeedUpdateUI thread ID " << QThread::currentThreadId();
    loadTasksFIM();
}

void FIMtasksWidget::slot_traineeSelected(QString login)
{
    qDebug() << "FIMtasksWidget::slot_traineeSelected thread ID " << QThread::currentThreadId();
    loginTraineeSelected = login;
}

void FIMtasksWidget::loadTasksFIM()
{
    //Обновление дерева
    treeWidget->clear();

    QByteArray array = connectorToServer->getListTaskFimArray();
    loadFIMtasksFromXML(array);

    //собственно обновление дерева
    fillTree();
}

TaskAmmFim* FIMtasksWidget::getTaskByID(int id)
{
    for(int i = 0; i < listTaskAmmFim.count(); i++)
    {/*Задачи*/
        TaskAmmFim* task = listTaskAmmFim.at(i);
        if(task->id == id)
            return task;
    }

    return nullptr;
}

void FIMtasksWidget::deleteAllTaskAmmFim()
{
    for(TaskAmmFim* task: listTaskAmmFim)
        delete task;

    listTaskAmmFim.clear();
}

void FIMtasksWidget::updateTaskItem(QTreeWidgetItem *itemTask)
{
    for (int i = 0; i < itemTask->childCount(); i++)
    {
        QTreeWidgetItem* itemMalfunction = itemTask->child(i);
        itemMalfunction->setCheckState(0, Qt::Checked);
        itemMalfunction->setExpanded(false);
    }
    itemTask->setExpanded(false);
}

void FIMtasksWidget::on_btnUpdateTasks_clicked()
{
    connectorToServer->sendQueryTasksXML("fim");
}

void FIMtasksWidget::on_btnAssignTaskToTrainee_clicked()
{
    QTreeWidgetItem *current = treeWidget->currentItem();

    if(current == nullptr)
        return;

    int id = current->text(ColumnsTree::clmn_ID).toInt();

    TaskAmmFim* task = getTaskByID(id);

    if(task)
    {
        int trainee_id = connectorToServer->getIdTraineeByLogin(loginTraineeSelected);

        TaskAmmFim taskNew;
        taskNew.title = task->title;

        connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_ASSIGN_TASK_FIM_TO_TRAINEE, trainee_id, &taskNew);

        updateTaskItem(current);
    }
}
