#include <QMessageBox>
#include "editorinstructors.h"
#include "viewerinstructors.h"
#include "ui_viewerinstructors.h"

ViewerInstructors::ViewerInstructors(ConnectorToServer* connectorToServer, QWidget *parent) :
    InstructorsView(connectorToServer, CommonView::TypeView::onlyView, parent),
    dlgRedactor(nullptr),
    ui(new Ui::ViewerInstructors)
{
    ui->setupUi(this);

    connect(treeWidget, &QTreeWidget::itemClicked, this, &ViewerInstructors::on_treeWidgetItemClicked);

    ui->horizontalLayout_1->addWidget(treeWidget);

    //treeWidget->setSelectionMode(QAbstractItemView::NoSelection);

    preparationTreeWidget();
    setNotLoggedInVisible(true);

    ui->btnEditorInstructors->setVisible(false);
}

ViewerInstructors::~ViewerInstructors()
{
    if(dlgRedactor)
        dlgRedactor->close();
    delete ui;
}

void ViewerInstructors::setAuthComplited(bool authComplited)
{
    this->authComplited = authComplited;
    updateButtons();
}

void ViewerInstructors::deactivate()
{
    if(dlgRedactor)
        dlgRedactor->close();

    CommonView::deactivate();
    updateButtons();
}

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

        reSetHeadTreeWidget();
        slot_NeedUpdateUI(true, false);
    }
}

void ViewerInstructors::on_btnEditorInstructors_clicked()
{
    connectorToServer->sendQueryBlockAuth(true);

    dlgRedactor = new DialogRedactorInstructors(connectorToServer, adminMode, this);
    dlgRedactor->exec();

    if(dlgRedactor)
    {
        delete dlgRedactor;
        dlgRedactor = nullptr;
    }

    if(authComplited)
        loadInstructorsFromDB();

    connectorToServer->sendQueryBlockAuth(false);
}

void ViewerInstructors::on_treeWidgetItemClicked(QTreeWidgetItem *item, int column)
{
    if(item == nullptr)
        return;

    //if(current->childCount() == 0)
    {//Выбран обучаемый
        QString login = item->text(ColumnsTreeUsers::clmn_Login);
        //if(login != "")
        {
            int newCurrentID = connectorToServer->getIdInstructorByLogin(login);

            //if(newCurrentID == lastCurrentID)
                //return;

            lastCurrentID = newCurrentID;

            Q_EMIT signal_instructorSelected(newCurrentID);
        }
    }
}

void ViewerInstructors::updateButtons()
{
    if(adminMode && authComplited)
    {
        ui->btnEditorInstructors->setEnabled(true);
    }
    else
    {
        ui->btnEditorInstructors->setEnabled(false);
    }
}
