#include <QMessageBox>
#include "editorinstructors.h"
#include "dialogeditinstructor.h"
#include "ui_editorinstructors.h"

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

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

    ui->verticalLayout_1->addWidget(treeWidget);

    this->adminMode = adminMode;

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

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

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

void EditorInstructors::on_btnNewInstructor_clicked()
{
    if(int id_instructor = dbLMS->newInstructor())
    {
        loadInstructorsFromDB();
        setCurrentInstructor(id_instructor);

        DialogEditInstructor dlg(this);

        Instructor instructor = dbLMS->getInstructor(id_instructor);
        if(instructor.getID() == 0)
            return;

        dlg.setInstructor(instructor);

        while (true)
        {
            switch( dlg.exec() )
            {
            case QDialog::Accepted:
            {
                Instructor instructor_edit = dlg.getInstructor();

                if(int id_edit = dbLMS->editInstructor(instructor_edit))
                {//Отредактировано
                    loadInstructorsFromDB();
                    setCurrentInstructor(id_edit);
                    return;
                }
                else
                {
                    dlg.setInstructor(instructor_edit);
                    continue;
                }
            }
            case QDialog::Rejected:
                dbLMS->delInstructor(id_instructor);
                loadInstructorsFromDB();
                return;
            default:
                dbLMS->delInstructor(id_instructor);
                loadInstructorsFromDB();
                return;
            }
        }
    }
}

void EditorInstructors::on_btnDeleteInstructor_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent == nullptr)
        {//Выбран Инструктор

            int id = treeItemCurrent->text(ColumnsTreeInsructors::clmn_ID).toInt();

            if(dbLMS->isAdminInstructor(id))
            {//Это Админ!
                QMessageBox::critical(this, tr("Error!"), tr("You cannot delete the Administrator."));
                return;
            }

            if(dbLMS->isLoggedInInstructor(id))
            {//Инструктор залогирован!
                QMessageBox::critical(this, tr("Error!"), tr("You cannot delete a logged-in instructor."));
                return;
            }

            if(QMessageBox::warning(this, tr("Attention!"), tr("The deletion will be irrevocable.\nDelete it anyway?"), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
            {
                if(dbLMS->delInstructor(id))
                    loadInstructorsFromDB();
            }
        }
    }
}

void EditorInstructors::on_btnToOrFromArchive_clicked()
{
    QTreeWidgetItem *treeItemCurrent = treeWidget->currentItem();

    if(treeItemCurrent != nullptr)
    {
        QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
        if(treeItemParent == nullptr)
        {//Выбран Инструктор

            int id = treeItemCurrent->text(ColumnsTreeInsructors::clmn_ID).toInt();

            Instructor instructor = dbLMS->getInstructor(id);
            if(instructor.getID() == 0)
                return;

            if(instructor.getArchived())
            {//Архивный
                instructor.setArchived(false);
                if(int id_edit = dbLMS->editInstructor(instructor))
                {
                    loadInstructorsFromDB();
                    setCurrentInstructor(id_edit);
                }
            }
            else
            {//Не Архивный
                if(dbLMS->isLoggedInInstructor(id))
                {//Инструктор залогирован!
                    QMessageBox::critical(this, tr("Error!"), tr("You cannot archive a logged-in instructor."));
                    return;
                }

                instructor.setArchived(true);
                if(int id_edit = dbLMS->editInstructor(instructor))
                {
                    if(!archiveVisible)
                        ui->btnArchive->click();

                    loadInstructorsFromDB();
                    setCurrentInstructor(id_edit);
                }
            }
        }
    }
}

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

    if(treeItemCurrent == nullptr)
        return;

    QTreeWidgetItem *treeItemParent = treeItemCurrent->parent();
    if(treeItemParent == nullptr)
    {//Выбран Инструктор

        int id = treeItemCurrent->text(ColumnsTreeInsructors::clmn_ID).toInt();

        if(dbLMS->isLoggedInInstructor(id))
        {//Инструктор залогирован!
            QMessageBox::critical(this, tr("Error!"), tr("You cannot archive a logged-in instructor."));
            return;
        }

        DialogEditInstructor dlg(this);

        Instructor instructor = dbLMS->getInstructor(id);
        if(instructor.getID() == 0)
            return;

        dlg.setInstructor(instructor);

        while (true)
        {
            switch( dlg.exec() )
            {
            case QDialog::Accepted:
            {
                Instructor instructor_edit = dlg.getInstructor();

                if(int id_edit = dbLMS->editInstructor(instructor_edit))
                {//Отредактировано
                    loadInstructorsFromDB();
                    setCurrentInstructor(id_edit);
                    return;
                }
                else
                {
                    dlg.setInstructor(instructor_edit);
                    continue;
                }

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

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

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

    if(current == nullptr)
        return;

    QTreeWidgetItem *treeItemParent = current->parent();
    if(treeItemParent == nullptr)
    {//Выбран инструктор

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

        if(dbLMS->isArchivedInstructor(id))
        {//Архивный
            ui->btnToOrFromArchive->setText(tr("From archive"));
            ui->btnToOrFromArchive->setIcon(QIcon(QStringLiteral(":/icons/instructorFromArchive.png")));
        }
        else
        {//Не Архивный
            ui->btnToOrFromArchive->setText(tr("To archive"));
            ui->btnToOrFromArchive->setIcon(QIcon(QStringLiteral(":/icons/instructorArchive.png")));
        }

        ui->btnNewInstructor->setEnabled(true);        

        if(dbLMS->isAdminInstructor(id) || dbLMS->isLoggedInInstructor(id))
        {//Это Админ или залогированный! Удалять/Архивировать/Редактировать нельзя!
            ui->btnDeleteInstructor->setEnabled(false);
            ui->btnToOrFromArchive->setEnabled(false);
            ui->btnEdit->setEnabled(false);
        }
        else
        {
            ui->btnToOrFromArchive->setEnabled(true);

            if(dbLMS->isArchivedInstructor(id))
                ui->btnDeleteInstructor->setEnabled(true);
            else
                ui->btnDeleteInstructor->setEnabled(false);

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

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

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