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

AMMtasksWidget::AMMtasksWidget(ConnectorToServer* connectorToServer, TypeList type, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AMMtasksWidget),
    connectorToServer(connectorToServer),
    treeWidget(nullptr),
    type(type),
    loginTraineeSelected(""),
    threadPreparation(nullptr),
    threadAnimation(nullptr),
    taskTreePreparation(nullptr),
    waitAnimationWidget(nullptr)
{
    ui->setupUi(this);

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

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

    connect(treeWidget, &QTreeWidget::currentItemChanged, this, &AMMtasksWidget::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);
    }

    threadPreparation = new QThread();
    taskTreePreparation = new TaskTreePreparation();
    taskTreePreparation->moveToThread(threadPreparation);
    threadPreparation->start();
    threadPreparation->setPriority(QThread::HighestPriority);
    connect(this, &AMMtasksWidget::signal_prepareListItems, taskTreePreparation, &TaskTreePreparation::slot_prepareListItems);
    connect(taskTreePreparation, &TaskTreePreparation::signal_listItemsReady, this, &AMMtasksWidget::slot_listItemsReady);

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

AMMtasksWidget::~AMMtasksWidget()
{
    delete ui;
}

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

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

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

    Module* module = searchModuleByID(id);

    if(module)
    {
        QString type = "Code";
        QString code = "";

        if(module->getType() == ModuleType::TYPE_PM)
        {
            PM* PMmodul = static_cast<PM*>(module);
            type = "PM";
            code = PMmodul->pmCode();
            ui->btnAssignTaskToTrainee->setEnabled(false);
        }
        else
        {
            DM* DMmodul = static_cast<DM*>(module);
            type = "DM";
            code = DMmodul->dmCode();
            ui->btnAssignTaskToTrainee->setEnabled(true);
        }

        ui->label->setText(type + " Code");
        ui->editCode->setText(code);
    }
    else
        ui->btnAssignTaskToTrainee->setEnabled(false);
}

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

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

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

    waitAnimationWidget->showWithPlay();

    QByteArray array = connectorToServer->getListTaskAmmArray();

    signal_prepareListItems(array, &listAllModules);
}

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

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

    waitAnimationWidget->hideWithStop();
}

Module *AMMtasksWidget::searchModuleByID(int id)
{
    Module* ptrModule = nullptr;

    for(Module* module: listAllModules)
    {
        ptrModule = module->getModuleByID(id);
        if(ptrModule)
            return ptrModule;
    }

    return nullptr;
}

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

    reSetHeadTreeWidget();

    treeWidget->setColumnWidth(ColumnsTree::clmn_ID, 80);
    treeWidget->setColumnWidth(ColumnsTree::clmn_PMorDM, 900);
    treeWidget->setColumnWidth(ColumnsTree::clmn_code, 200);

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

void AMMtasksWidget::reSetHeadTreeWidget()
{
    QStringList listHeaders = {tr("PM/DM"), tr("Code"), tr("ID")};
    treeWidget->setHeaderLabels(listHeaders);
}

void AMMtasksWidget::on_btnUpdateTasks_clicked()
{
    connectorToServer->sendQueryTasksXML("amm");
}

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

    if(current == nullptr)
        return;

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

    Module* module = searchModuleByID(id);

    if(module)
    {
        if(module->getType() == ModuleType::TYPE_DM)
        {
            QString dmCode = "";
            QString techName = "";
            DM* DMmodul = static_cast<DM*>(module);
            dmCode = DMmodul->dmCode();
            techName = DMmodul->getLangStructRus().techName;

            int trainee_id = connectorToServer->getIdTraineeByLogin(loginTraineeSelected);

            TaskAmmFim taskNew;
            taskNew.ammProcedure.title = techName;
            taskNew.ammProcedure.dmCode = dmCode;

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