#include <QFile>
#include <QXmlStreamReader>
#include <QDomDocument>
#include <QMessageBox>
#include <QThread>
#include <QResizeEvent>
#include "ammtaskswidget.h"
#include "ui_ammtaskswidget.h"
#include "dialogchecktask.h"

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

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

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

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

    preparationTreeWidget();

    threadPreparation = new QThread();
    taskTreePreparation = new TaskAMMFIMTreePreparation(type);
    taskTreePreparation->moveToThread(threadPreparation);
    threadPreparation->start();
    threadPreparation->setPriority(QThread::HighestPriority);
    connect(this, &AMMtasksWidget::signal_prepareAMMListItems, taskTreePreparation, &TaskAMMFIMTreePreparation::slot_prepareAMMListItems);
    connect(this, &AMMtasksWidget::signal_prepareAMMListItemsForTrainee, taskTreePreparation, &TaskAMMFIMTreePreparation::slot_prepareAMMListItemsForTrainee);
    connect(taskTreePreparation, &TaskAMMFIMTreePreparation::signal_listAMMItemsReady, this, &AMMtasksWidget::slot_AMMlistItemsReady);
    connect(this, &AMMtasksWidget::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->btnOnlyActive->setObjectName("btnOnlyActive");
    ui->btnOnlyActive->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->btnOnlyActive);
        //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
    {
        ui->btnOnlyActive->setVisible(false);
        ui->btnAssignTask->setVisible(false);

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

    //ui->btnCheck->setVisible(false);
}

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

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

    delete threadPreparation;

    delete taskTreePreparation;
    delete waitAnimationWidget;
    delete treeWidget;

    delete ui;
}

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

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

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

    int width = treeWidget->width();

    treeWidget->setColumnWidth(ColumnsTreeAMM::clmnAMM_ID, 50);
    treeWidget->setColumnWidth(ColumnsTreeAMM::clmnAMM_code, 250);
    treeWidget->setColumnWidth(ColumnsTreeAMM::clmnAMM_status, 110);

    int widthPMorDM;
    if(type == TypeListTreeAMMFIM::listCommon)
        widthPMorDM = width - (250 + 10);
    else
        widthPMorDM = width - (410 + 10);

    treeWidget->setColumnWidth(ColumnsTreeAMM::clmnAMM_PMorDM, widthPMorDM);
}

void AMMtasksWidget::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_UpdateTasksAMMforTrainee(idTraineeSelected);
    }
}

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

    int id = current->text(ColumnsTreeAMM::clmnAMM_ID).toInt();

    if(taskTreePreparation->getTypeModuleAMMbyID(id) == ModuleType::TYPE_PM)
        ui->btnAssignTask->setEnabled(false);
    else
        ui->btnAssignTask->setEnabled(true);
}

void AMMtasksWidget::slot_NeedUpdateUI()
{
    qDebug() << "AMMtasksWidget::slot_NeedUpdateUI thread ID " << QThread::currentThreadId();
    loadTasksAMM();
}

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

    idTraineeSelected = id_trainee;

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

void AMMtasksWidget::slot_UpdateTasksAMMforTrainee(int trainee_id)
{
    qDebug() << "slot_UpdateTasksAMMforTrainee" << QThread::currentThreadId();
    if(type == TypeListTreeAMMFIM::listForTrainee)
    {
        if(idTraineeSelected == trainee_id)
        {
            QList<TaskAmmFim> listTask = connectorToServer->getListTasksAMMforTrainee(trainee_id);
            signal_prepareAMMListItemsForTrainee(listTask);

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

void AMMtasksWidget::loadTasksAMM(bool flRequestFirst)
{
    //Обновление дерева
    treeWidget->clear();

    waitAnimationWidget->showWithPlay();

    QByteArray arrayAMM;

    //if(flRequestFirst)
    arrayAMM = connectorToServer->getListTaskAmmArray();

    emit signal_prepareAMMListItems(arrayAMM, flOnlyActive, flRequestFirst);
}

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

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

    QTreeWidgetItem * item = treeWidget->topLevelItem(0);
    if(item != nullptr)
        treeWidget->setCurrentItem(item);

    waitAnimationWidget->hideWithStop();

    ui->btnOnlyActive->setEnabled(true);
}

void AMMtasksWidget::preparationTreeWidget()
{
    treeWidget->setColumnCount(clmnAMM_count);

    reSetHeadTreeWidget();

    if(type == TypeListTreeAMMFIM::listCommon)
    {
        treeWidget->setColumnHidden(ColumnsTreeAMM::clmnAMM_ID, true);
        treeWidget->setColumnHidden(ColumnsTreeAMM::clmnAMM_status, true);
    }
}

void AMMtasksWidget::reSetHeadTreeWidget()
{
    QStringList listHeaders;

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


    treeWidget->setHeaderLabels(listHeaders);
}

void AMMtasksWidget::assignTaskAMMtoTrainee()
{
    QTreeWidgetItem *current = treeWidget->currentItem();

    if(current == nullptr)
        return;

    int id = current->text(ColumnsTreeAMM::clmnAMM_ID).toInt();

    TaskAmmFim taskNew = taskTreePreparation->getTaskAMMbyID(id);

    if(taskNew.getID())
    {
        emit signal_AssignedTask();
        connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_ASSIGN_TASK_AMM_TO_TRAINEE, idTraineeSelected, &taskNew);
    }
}

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

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

            int id = treeItemCurrent->text(ColumnsTreeAMM::clmnAMM_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_AMM_TO_TRAINEE, id);
            }
        }
    }
}

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

    if(treeItemCurrent != nullptr)
    {//Выбрана задача

        int id = treeItemCurrent->text(ColumnsTreeAMM::clmnAMM_ID).toInt();

        TaskAmmFim task = taskTreePreparation->getTaskAMMbyID(id);

        if(!task.getID())
            return;

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

        dlg.setTask(&task);

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

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

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

void AMMtasksWidget::on_btnOnlyActive_clicked()
{
    if(ui->btnOnlyActive->isChecked())
    {
        flOnlyActive = true;
    }
    else
    {
        flOnlyActive = false;
    }
    loadTasksAMM(false);
}
