#include <QMessageBox>
#include "editortrainees.h"
#include "ui_editortrainees.h"
#include "dialogeditgroup.h"
#include "dialogedittrainee.h"

EditorTrainees::EditorTrainees(InterfaceDataBaseLMS* dbLMS, bool adminMode, QWidget *parent) :
    TraineesView(dbLMS, CommonView::TypeView::control, parent),
    ui(new Ui::EditorTrainees)
{
    ui->setupUi((QDialog*)this);

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

    ui->verticalLayout_1->addWidget(treeWidget);

    this->adminMode = adminMode;

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

    if(adminMode)
        ui->btnArchive->click();
}

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

void EditorTrainees::on_btnNewGroup_clicked()
{
    if(int id_group = dbLMS->newGroup())
    {
        loadTraineesFromDB();
        setCurrentGroup(id_group);

        DialogEditGroup dlg(this);

        Group group = dbLMS->getGroup(id_group);
        if(group.getID() == 0)
            return;

        dlg.setGroup(group);

        while (true)
        {
            switch( dlg.exec() )
            {
            case QDialog::Accepted:
            {
                Group group_edit = dlg.getGroup();

                if(int id_edit = dbLMS->editGroup(group_edit))
                {//Отредактировано
                    loadTraineesFromDB();
                    setCurrentGroup(id_edit);
                    return;
                }
                else
                {
                    dlg.setGroup(group_edit);
                    continue;
                }

            }
            case QDialog::Rejected:
                dbLMS->delGroup(id_group);
                loadTraineesFromDB();
                return;
            default:
                dbLMS->delGroup(id_group);
                loadTraineesFromDB();
                return;
            }
        }
    }
}

void EditorTrainees::on_btnDeleteGroup_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent == nullptr)
        {//Выбрана группа
            int id_group = treeItemCurrent->text(ColumnsTreeTrainees::clmn_ID).toInt();

            if(dbLMS->getListTraineesInGroup(id_group).count() > 0)
            {
                QMessageBox::critical(this, tr("Editing error!"), tr("The group is not empty.\nIt is not possible to delete a non-empty group."));
                return;
            }
            else
            {//Пустая группа
                if(QMessageBox::warning(this, tr("Attention!"), tr("The deletion will be irrevocable.\nDelete anyway?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
                {
                    if(int id = dbLMS->delGroup(id_group))
                    {//Удалено
                        loadTraineesFromDB();
                    }
                    else
                    {
                        //Ошибка удаления
                    }
                }
            }
        }
    }
}

void EditorTrainees::on_btnNewTrainee_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent == nullptr)
        {//Выбрана группа. Можно добавить Обучаемого
            int id_group = treeItemCurrent->text(ColumnsTreeTrainees::clmn_ID).toInt();
            if(int id_trainee = dbLMS->newTrainee(id_group))
            {
                loadTraineesFromDB();
                setCurrentGroup(id_group);

                DialogEditTrainee dlg(this);

                Trainee trainee = dbLMS->getTrainee(id_trainee);
                if(trainee.getID() == 0)
                    return;

                dlg.setTrainee(trainee);

                while (true)
                {
                    switch( dlg.exec() )
                    {
                    case QDialog::Accepted:
                        {
                            Trainee trainee_edit = dlg.getTrainee();

                            if(int id_edit = dbLMS->editTrainee(trainee_edit))
                            {//Отредактировано
                                loadTraineesFromDB();
                                //setCurrentTrainee(id_edit);
                                setCurrentGroup(id_group);
                                return;
                            }
                            else
                            {
                                dlg.setTrainee(trainee_edit);
                                continue;
                            }

                            break;
                        }
                    case QDialog::Rejected:
                        dbLMS->delTrainee(id_trainee);
                        loadTraineesFromDB();
                        setCurrentGroup(id_group);
                        return;
                    default:
                        dbLMS->delTrainee(id_trainee);
                        loadTraineesFromDB();
                        setCurrentGroup(id_group);
                        return;
                    }
                }
            }
        }
    }
}

void EditorTrainees::on_btnDeleteTrainee_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent != nullptr)
        {//Выбран обучаемый

            int id_trainee = treeItemCurrent->text(ColumnsTreeTrainees::clmn_ID).toInt();
            int id_group = treeItemParent->text(ColumnsTreeTrainees::clmn_ID).toInt();

            if(dbLMS->isLoggedInTrainee(id_trainee))
            {//Обучаемый залогирован!
                QMessageBox::critical(this, tr("Error!"), tr("You cannot delete a logged-in trainee."));
                return;
            }

            if(QMessageBox::warning(this, tr("Attention!"), tr("The deletion will be irrevocable.\nDelete anyway?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
            {
                if(int id = dbLMS->delTrainee(id_trainee))
                {//Удалено
                    loadTraineesFromDB();
                    setCurrentGroup(id_group);
                }
                else
                {
                    //Ошибка удаления
                }
            }
        }
    }
}

void EditorTrainees::on_btnToOrFromArchiveTrainee_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent != nullptr)
        {//Выбран обучаемый

            int id_trainee = treeItemCurrent->text(ColumnsTreeTrainees::clmn_ID).toInt();

            Trainee trainee = dbLMS->getTrainee(id_trainee);
            if(trainee.getID() == 0)
                return;

            if(trainee.getArchived())
            {//Архивный
                trainee.setArchived(false);
                if(int id = dbLMS->editTrainee(trainee))
                {//Отредактировано
                    loadTraineesFromDB();
                    setCurrentTrainee(id);
                }
                else
                {
                    //Ошибка редактирования
                }
            }
            else
            {//Не Архивный                
                if(dbLMS->isLoggedInTrainee(id_trainee))
                {//Обучаемый залогирован!
                    QMessageBox::critical(this, tr("Error!"), tr("You cannot archive a logged-in trainee."));
                    return;
                }

                trainee.setArchived(true);
                if(int id = dbLMS->editTrainee(trainee))
                {//Отредактировано
                    if(!archiveVisible)
                        ui->btnArchive->click();

                    loadTraineesFromDB();
                    setCurrentTrainee(id);
                }
                else
                {
                    //Ошибка редактирования
                }
            }
        }
    }
}

void EditorTrainees::on_btnEdit_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent == nullptr)
        return;

    QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
    if(treeItemParent == nullptr)
    {//Выбрана группа

        int id_group = treeItemCurrent->text(ColumnsTreeTrainees::clmn_ID).toInt();

        DialogEditGroup dlg(this);

        Group group = dbLMS->getGroup(id_group);
        if(group.getID() == 0)
            return;

        dlg.setGroup(group);

        while (true)
        {
            switch( dlg.exec() )
            {
            case QDialog::Accepted:
            {
                Group group_edit = dlg.getGroup();

                if(int id = dbLMS->editGroup(group_edit))
                {//Отредактировано
                    loadTraineesFromDB();
                    setCurrentGroup(id);
                    return;
                }
                else
                {
                    dlg.setGroup(group_edit);
                    continue;
                }

                break;
            }
            case QDialog::Rejected:
                return;
                break;
            default:
                return;
                break;
            }
        }
    }
    else
    {//Выбран обучаемый

        int id_trainee = treeItemCurrent->text(ColumnsTreeTrainees::clmn_ID).toInt();

        if(dbLMS->isLoggedInTrainee(id_trainee))
        {//Обучаемый залогирован!
            QMessageBox::critical(this, tr("Error!"), tr("You cannot archive a logged-in trainee."));
            return;
        }

        DialogEditTrainee dlg(this);

        Trainee trainee = dbLMS->getTrainee(id_trainee);
        if(trainee.getID() == 0)
            return;

        dlg.setTrainee(trainee);

        while (true)
        {
            switch( dlg.exec() )
            {
            case QDialog::Accepted:
                {
                    Trainee trainee_edit = dlg.getTrainee();

                    if(int id = dbLMS->editTrainee(trainee_edit))
                    {//Отредактировано
                        loadTraineesFromDB();
                        setCurrentTrainee(id);
                        return;
                    }
                    else
                    {
                        dlg.setTrainee(trainee_edit);
                        continue;
                    }

                    break;
                }
            case QDialog::Rejected:
                return;
                break;
            default:
                return;
                break;
            }
        }
    }
}

void EditorTrainees::on_btnArchive_clicked()
{
    bool state = ui->btnArchive->isChecked();
    setArchiveVisible(state);
    loadTraineesFromDB();
}

void EditorTrainees::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    //Определяем доступность и функционал кнопок для выбранного элемента

    if(current == nullptr)
        return;

    QTreeWidgetItem *treeItemParent = current->parent();
    if(treeItemParent == nullptr)
    {//Выбрана группа
        int id_group = current->text(ColumnsTreeTrainees::clmn_ID).toInt();

        if(adminMode)
        {
            ui->btnNewGroup->setEnabled(true);

            if(dbLMS->getListTraineesInGroup(id_group).count() > 0)
            {//Группа не пуста
                ui->btnDeleteGroup->setEnabled(false);
            }
            else
            {//Группа пуста
                ui->btnDeleteGroup->setEnabled(true);
            }
        }
        else
        {
            ui->btnNewGroup->setEnabled(false);
            ui->btnDeleteGroup->setEnabled(false);
        }

        ui->btnNewTrainee->setEnabled(true);
        ui->btnDeleteTrainee->setEnabled(false);
        ui->btnToOrFromArchiveTrainee->setEnabled(false);
        ui->btnEdit->setEnabled(true);
        ui->btnArchive->setEnabled(true);

        ui->btnToOrFromArchiveTrainee->setText(tr("To archive"));
        ui->btnToOrFromArchiveTrainee->setIcon(QIcon(QStringLiteral(":/icons/traineeArchive.png")));
    }
    else
    {//Выбран обучаемый
        int id_trainee = current->text(ColumnsTreeTrainees::clmn_ID).toInt();

        ui->btnNewGroup->setEnabled(false);
        ui->btnDeleteGroup->setEnabled(false);
        ui->btnNewTrainee->setEnabled(false);        

        if(dbLMS->isArchivedTrainee(id_trainee))
        {//Архивный
            //ui->btnDeleteTrainee->setEnabled(true);

            ui->btnToOrFromArchiveTrainee->setText(tr("From archive"));
            ui->btnToOrFromArchiveTrainee->setIcon(QIcon(QStringLiteral(":/icons/traineeFromArchive.png")));
        }
        else
        {//Не Архивный
            //ui->btnDeleteTrainee->setEnabled(false);

            ui->btnToOrFromArchiveTrainee->setText(tr("To archive"));
            ui->btnToOrFromArchiveTrainee->setIcon(QIcon(QStringLiteral(":/icons/traineeArchive.png")));
        }

        if(dbLMS->isLoggedInTrainee(id_trainee))
        {//Это залогированный! Удалять/Архивировать/Редактировать нельзя!
            ui->btnDeleteTrainee->setEnabled(false);
            ui->btnToOrFromArchiveTrainee->setEnabled(false);
            ui->btnEdit->setEnabled(false);
        }
        else
        {
            ui->btnToOrFromArchiveTrainee->setEnabled(true);

            if(dbLMS->isArchivedTrainee(id_trainee))
                ui->btnDeleteTrainee->setEnabled(true);
            else
                ui->btnDeleteTrainee->setEnabled(false);

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

        //ui->btnToOrFromArchiveTrainee->setEnabled(true);

        //ui->btnEdit->setEnabled(true);
        ui->btnArchive->setEnabled(true);
    }
}

void EditorTrainees::setCurrentGroup(int id)
{
    for(int i = 0; i < treeWidget->topLevelItemCount(); i++)
    {
        QTreeWidgetItem * item = treeWidget->topLevelItem(i);
        if(item != nullptr)
            if(item->text(ColumnsTreeTrainees::clmn_ID).toInt() == id)
            {
                treeWidget->setCurrentItem(item);
                break;
            }
    }
}

void EditorTrainees::setCurrentTrainee(int id)
{
    for(int i = 0; i < treeWidget->topLevelItemCount(); i++)
    {
        QTreeWidgetItem * item = treeWidget->topLevelItem(i);
        if(item != nullptr)
        {
            for (int j = 0; j < item->childCount(); j++)
            {
                QTreeWidgetItem * itemChild = item->child(j);
                if(itemChild != nullptr)
                    if(itemChild->text(ColumnsTreeTrainees::clmn_ID).toInt() == id)
                    {
                        treeWidget->setCurrentItem(itemChild);
                        break;
                    }
            }//for (int j = 0; j < item->childCount(); j++)
        }
    }//for(int i = 0; i < treeWidget->topLevelItemCount(); i++)
}
