#include "editortrainees.h"
#include "viewertrainees.h"
#include "ui_viewertrainees.h"

ViewerTrainees::ViewerTrainees(InterfaceDataBaseLMS* db, QWidget *parent) :
    TraineesView(db, CommonView::TypeView::onlyView, parent),
    ui(new Ui::ViewerTrainees)
{
    ui->setupUi(this);

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

    ui->horizontalLayout_1->addWidget(treeWidget);

    preparationTreeWidget(/*ui->treeWidget*/);
    setNotLoggedInVisible(true);
}

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

/*
void ViewerTrainees::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
    if(item->childCount() == 0)
    {//Выбран обучаемый
        QString login = item->text(ColumnsTreeTrainees::clmn_Login);
        Q_EMIT signal_traineeSelected(login);
    }
}*/

void ViewerTrainees::slot_tabMessengerChanged(QString login)
{
    for (int i = 0; i < treeWidget->topLevelItemCount(); i++)
    {//Проход по группам
        int countChild = treeWidget->topLevelItem(i)->childCount();

        for (int j = 0; j < countChild; j++)
        {//Проход по обучаемым
            QString loginChild = treeWidget->topLevelItem(i)->child(j)->text(ColumnsTreeTrainees::clmn_Login);
            if(loginChild == login)
            {
                treeWidget->setCurrentItem(treeWidget->topLevelItem(i)->child(j));
                Q_EMIT signal_traineeSelected(login);
                return;
            }
        }
    }
}

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

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

void ViewerTrainees::on_btnEditorTrainees_clicked()
{
    Q_EMIT signal_BlockAutorization(true);

    EditorTrainees editorTraineesGroups(dbLMS, adminMode);
    QDialog* dialog = new QDialog(this);
    QHBoxLayout *layout = new QHBoxLayout(dialog);
    layout->addWidget(&editorTraineesGroups);
    dialog->setWindowTitle(tr("Editor of trainees"));
    dialog->setMinimumSize(1600, 800);
    dialog->exec();

    loadTraineesFromDB();

    Q_EMIT signal_BlockAutorization(false);
}

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

    if(current->childCount() == 0)
    {//Выбран обучаемый
        QString login = current->text(ColumnsTreeTrainees::clmn_Login);
        Q_EMIT signal_traineeSelected(login);
    }
}

void ViewerTrainees::updateButtons()
{
    if(authComplited)
    {
        ui->btnEditorTrainees->setEnabled(true);
    }
    else
    {
        ui->btnEditorTrainees->setEnabled(false);
    }
}
