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

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

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

    ui->horizontalLayout_1->addWidget(treeWidget);

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

    preparationTreeWidget();
    setNotLoggedInVisible(true);

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

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

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

void ViewerInstructors::deactivate()
{
    CommonView::deactivate();
    updateButtons();
}

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

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

void ViewerInstructors::on_btnEditorInstructors_clicked()
{
    Q_EMIT signal_BlockAutorization(true);

    EditorInstructors editorInstructors(connectorToServer, adminMode);
    connect(connectorToServer, &ConnectorToServer::signal_UpdateDB, &editorInstructors, &EditorInstructors::slot_NeedUpdateUI);

    QDialog* dialog = new QDialog(this);
    QHBoxLayout *layout = new QHBoxLayout(dialog);
    layout->addWidget(&editorInstructors);
    dialog->setWindowTitle(tr("Editor of instructors"));
    dialog->setMinimumSize(1600, 800);
    dialog->setStyleSheet(this->styleSheet());
    dialog->exec();

    loadInstructorsFromDB();

    Q_EMIT signal_BlockAutorization(false);
}

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

    //if(current->childCount() == 0)
    {//Выбран обучаемый
        QString login = item->text(ColumnsTreeInsructors::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);
    }
}
