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

FIMtasksWidget::FIMtasksWidget(ConnectorToServer* connectorToServer, TypeListTreeAMMFIM type, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FIMtasksWidget),
    connectorToServer(connectorToServer),
    treeWidget(nullptr),
    type(type),    
    idTraineeSelected(0),
    threadPreparation(nullptr),
    taskTreePreparation(nullptr),
    waitAnimationWidget(nullptr),
    userName("")
{
    ui->setupUi(this);

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

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

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

    preparationTreeWidget();

    threadPreparation = new QThread();
    taskTreePreparation = new TaskAMMFIMTreePreparation(type);
    taskTreePreparation->moveToThread(threadPreparation);
    threadPreparation->start();
    threadPreparation->setPriority(QThread::HighestPriority);
    connect(this, &FIMtasksWidget::signal_prepareFIMListItems, taskTreePreparation, &TaskAMMFIMTreePreparation::slot_prepareFIMListItems);
    connect(this, &FIMtasksWidget::signal_prepareFIMListItemsForTrainee, taskTreePreparation, &TaskAMMFIMTreePreparation::slot_prepareFIMListItemsForTrainee);
    connect(taskTreePreparation, &TaskAMMFIMTreePreparation::signal_listFIMItemsReady, this, &FIMtasksWidget::slot_FIMlistItemsReady);
    connect(this, &FIMtasksWidget::signal_stopParserPreparation, taskTreePreparation, &TaskAMMFIMTreePreparation::slot_stopParserPreparation);

    waitAnimationWidget = new WaitAnimationWidget;
    QMovie *movie = new QMovie(":/resources/icons/762.gif");
    waitAnimationWidget->setParent(this);
    waitAnimationWidget->initialize(movie,this);

    ui->btnDelete->setObjectName("btnDelete");
    ui->btnDelete->setEnabled(false);
    ui->btnCheck->setObjectName("btnCheck");
    ui->btnCheck->setEnabled(false);
    ui->btnAssignTask->setObjectName("btnAssignTask");
    ui->btnAssignTask->setEnabled(false);

    if(type == TypeListTreeAMMFIM::listCommon)
    {
        //ui->horizontalLayout_3->addWidget(ui->btnAssignTask);
        //ui->horizontalLayout_3->addWidget(ui->btnCheck);
        //ui->horizontalLayout_3->addWidget(ui->btnDelete);
        //ui->horizontalLayout_3->setAlignment(Qt::AlignmentFlag::AlignLeft);

        ui->btnDelete->setVisible(false);
        ui->btnCheck->setVisible(false);
    }
    else if(type == TypeListTreeAMMFIM::listOneTask)
    {
        ui->btnDelete->setVisible(false);
        ui->btnCheck->setVisible(false);
        ui->btnAssignTask->setVisible(false);
        this->treeWidget->headerItem()->setHidden(true);
        this->treeWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);        
    }
    else
    {
        ui->btnAssignTask->setVisible(false);

        //ui->verticalLayout->setAlignment(Qt::AlignmentFlag::AlignBottom);
        //ui->horizontalLayout_3->setAlignment(Qt::AlignmentFlag::AlignLeft);
    }
}

FIMtasksWidget::~FIMtasksWidget()
{
    waitAnimationWidget->hideWithStop();
    emit signal_stopParserPreparation();

    threadPreparation->quit();
    threadPreparation->wait();

    delete threadPreparation;

    delete taskTreePreparation;
    delete waitAnimationWidget;
    delete treeWidget;

    delete ui;
}

void FIMtasksWidget::deactivate()
{
    ui->btnAssignTask->setEnabled(false);
    treeWidget->clear();
    idTraineeSelected = 0;
}

void FIMtasksWidget::setOneTaskFim(TaskAmmFim* task)
{
    QList<TaskAmmFim> listTask;
    listTask.append(*task);
    emit signal_prepareFIMListItemsForTrainee(listTask);
}

void FIMtasksWidget::resizeEvent(QResizeEvent *event)
{
    QSize size = event->size();
    waitAnimationWidget->resize(size);

    int width = treeWidget->width();

    treeWidget->setColumnWidth(ColumnsTreeFIM::clmnFIM_ID, 50);
    treeWidget->setColumnWidth(ColumnsTreeFIM::clmnFIM_status, 110);

    int widthTitle;
    if(type == TypeListTreeAMMFIM::listCommon)
        widthTitle = width - (0 + 10);
    else
        widthTitle = width - (160 + 10);

    treeWidget->setColumnWidth(ColumnsTreeFIM::clmnFIM_Title, widthTitle);
}

void FIMtasksWidget::changeEvent(QEvent *event)
{
    // В случае получения события изменения языка приложения
    if (event->type() == QEvent::LanguageChange)
    {// переведём окно заново
        ui->retranslateUi(this);

        reSetHeadTreeWidget();

        if(type == TypeListTreeAMMFIM::listCommon)
        {
            //slot_NeedUpdateUI();
        }
        else if(type == TypeListTreeAMMFIM::listForTrainee)
            if(idTraineeSelected)
                slot_UpdateTasksFIMforTrainee(idTraineeSelected);
    }
}

void FIMtasksWidget::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    if(current == nullptr)
    {
        ui->btnDelete->setEnabled(false);
        ui->btnCheck->setEnabled(false);
        return;
    }

    QString code = "";

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

        TaskAmmFim task = taskTreePreparation->getTaskFIMbyID(id);

        if(!task.getID())
        {
            ui->btnAssignTask->setEnabled(false);

            ui->btnDelete->setEnabled(false);
            ui->btnCheck->setEnabled(false);
        }

        code = task.title;

        ui->btnAssignTask->setEnabled(true);

        ui->btnDelete->setEnabled(true);

        if(task.status != "new")
            ui->btnCheck->setEnabled(true);
        else
            ui->btnCheck->setEnabled(false);
    }
    else
    {
        ui->btnAssignTask->setEnabled(false);

        ui->btnDelete->setEnabled(false);
        ui->btnCheck->setEnabled(false);
    }
}

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

void FIMtasksWidget::slot_traineeSelected(int id_trainee)
{
    qDebug() << "FIMtasksWidget::slot_traineeSelected thread ID " << QThread::currentThreadId();

    idTraineeSelected = id_trainee;

    if(type == TypeListTreeAMMFIM::listForTrainee)
    {
        waitAnimationWidget->showWithPlay();
        connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_GET_TASKS_FIM_FOR_TRAINEE, idTraineeSelected);
    }
}

void FIMtasksWidget::slot_UpdateTasksFIMforTrainee(int trainee_id)
{
    qDebug() << "slot_UpdateTasksFIMforTrainee" << QThread::currentThreadId();
    if(type == TypeListTreeAMMFIM::listForTrainee)
    {
        if(idTraineeSelected == trainee_id)
        {
            QList<TaskAmmFim> listTask = connectorToServer->getListTasksFIMforTrainee(trainee_id);
            emit signal_prepareFIMListItemsForTrainee(listTask);

            emit signal_countTasksFIMforTraineeChanged(trainee_id, listTask.count());
        }
    }
}

void FIMtasksWidget::waitAnimationWidgetShowWithPlay()
{
    waitAnimationWidget->showWithPlay();
}

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

    waitAnimationWidget->showWithPlay();

    QByteArray arrayFIM = connectorToServer->getListTaskFimArray();

    emit signal_prepareFIMListItems(arrayFIM);
}

void FIMtasksWidget::slot_FIMlistItemsReady(QList<QTreeWidgetItem *> listItems)
{
    //Обновление дерева
    treeWidget->clear();

    for(QTreeWidgetItem * item : listItems)
        treeWidget->addTopLevelItem(item);

    QTreeWidgetItem * item = treeWidget->topLevelItem(0);
    if(item != nullptr)
    {
        treeWidget->setCurrentItem(item);
        if(type == TypeListTreeAMMFIM::listOneTask)
            treeWidget->expandAll();
    }

    waitAnimationWidget->hideWithStop();
}

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

    reSetHeadTreeWidget();

    if(type == TypeListTreeAMMFIM::listCommon || type == TypeListTreeAMMFIM::listOneTask)
    {
        treeWidget->setColumnHidden(ColumnsTreeFIM::clmnFIM_ID, true);
        treeWidget->setColumnHidden(ColumnsTreeFIM::clmnFIM_status, true);
    }
}

void FIMtasksWidget::reSetHeadTreeWidget()
{
    QStringList listHeaders;

    if(type == TypeListTreeAMMFIM::listForTrainee)
        listHeaders = QStringList{tr("Task FIM"), tr("ID"), tr("Status")};
    else
        listHeaders = QStringList{tr("Task FIM"), tr("ID"), tr("Status")};

    treeWidget->setHeaderLabels(listHeaders);
}

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

    if(current == nullptr)
        return;

    int id = current->text(ColumnsTreeFIM::clmnFIM_ID).toInt();

    TaskAmmFim task = taskTreePreparation->getTaskFIMbyID(id);

    if(task.getID())
    {
        TaskAmmFim taskNew;
        taskNew.title = task.title;

        //Назначенные неисправности
        for (int i = 0; i < current->childCount(); i++)
        {
            QTreeWidgetItem* itemMalfunction = current->child(i);

            if(itemMalfunction->checkState(0) == Qt::Checked)
            {
                Malfunction malfunction = task.malfunctionList.at(i);
                taskNew.malfunctionList.append(malfunction);
            }
        }

        emit signal_AssignedTask();
        connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_ASSIGN_TASK_FIM_TO_TRAINEE, idTraineeSelected, &taskNew);

        updateTaskItem(current);
    }
}

void FIMtasksWidget::on_btnDelete_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent == nullptr)
        {//Выбрана задача

            int id = treeItemCurrent->text(ColumnsTreeFIM::clmnFIM_ID).toInt();

            if(QMessageBox::warning(this, tr("Attention!"), tr("The deletion will be irrevocable.\nDelete it anyway?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
            {
                waitAnimationWidget->showWithPlay();
                connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_DEL_TASK_FIM_TO_TRAINEE, id);
            }
        }
    }
}

void FIMtasksWidget::on_btnCheck_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent == nullptr)
        {//Выбрана задача

            int id = treeItemCurrent->text(ColumnsTreeFIM::clmnFIM_ID).toInt();

            TaskAmmFim task = taskTreePreparation->getTaskFIMbyID(id);

            if(!task.getID())
                return;

            DialogCheckTask dlg(connectorToServer, "fim", this);

            dlg.setTask(&task);

            QDialog* dialog = new QDialog(this);
            QHBoxLayout *layout = new QHBoxLayout(dialog);
            layout->addWidget(&dlg);
            dialog->setWindowTitle(tr("Check Task"));
            dialog->setMinimumSize(1600, 800);
            dialog->setStyleSheet(this->styleSheet());
            dialog->exec();

            if(dlg.getFlChanged())
                waitAnimationWidget->showWithPlay();
        }
    }
}

void FIMtasksWidget::on_btnAssignTask_clicked()
{
    if(QMessageBox::question(this, tr("New task"), tr("Assign this task?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
        assignTaskFIMtoTrainee();
}

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);
}


