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

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

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

    ui->verticalLayout_1->addWidget(treeWidget);

    this->adminMode = adminMode;

    preparationTreeWidget();
    //setNotLoggedInVisible(true);
    loadInstructorsFromDB();

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

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

void EditorInstructors::on_btnNewInstructor_clicked()
{
    Instructor instructor;
    Instructor instructor_edit;

    if(editInstructor(instructor, &instructor_edit))
       connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_NEW_INSTRUCTOR, 0, &instructor_edit);

    return;
/*
    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(connectorToServer->isAdminInstructor(id))
            {//Это Админ!
                QMessageBox::critical(this, tr("Error!"), tr("You cannot delete the Administrator."));
                return;
            }

            if(connectorToServer->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)
            {
                connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_DEL_INSTRUCTOR, id);
            }
        }
    }
}

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 = connectorToServer->getInstructor(id);
            if(instructor.getID() == 0)
                return;

            if(connectorToServer->isArchivedInstructor(id))
            {//Архивный
                instructor.setArchived(false);
                connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_EDIT_INSTRUCTOR, id, &instructor);
            }
            else
            {//Не Архивный
                if(connectorToServer->isLoggedInInstructor(id))
                {//Инструктор залогирован!
                    QMessageBox::critical(this, tr("Error!"), tr("You cannot archive a logged-in instructor."));
                    return;
                }

                instructor.setArchived(true);
                connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_EDIT_INSTRUCTOR, id, &instructor);
                if(!archiveVisible)
                    ui->btnArchive->click();
                /*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(connectorToServer->isLoggedInInstructor(id))
        {//Инструктор залогирован!
            QMessageBox::critical(this, tr("Error!"), tr("You cannot edit a logged-in instructor."));
            return;
        }

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

        Instructor instructor_edit;

        if(editInstructor(instructor, &instructor_edit))
            connectorToServer->sendQueryToDB(TypeQueryToDB::TYPE_QUERY_EDIT_INSTRUCTOR, id, &instructor_edit);
    }
}

void EditorInstructors::on_btnArchive_clicked()
{
    bool state = ui->btnArchive->isChecked();    
    setArchiveVisible(state);
    if(!state)
    {
        lastCurrentID = 0;
    }
    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();

        lastCurrentID = id;

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

        ui->btnNewInstructor->setEnabled(true);        

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

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

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

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

bool EditorInstructors::verifyInstructor(Instructor instructor)
{
    //Проверка корректности логина, имени, пароля

    if(instructor.getName() == QStringLiteral("<instructor>"))
    {//Имя не корректно!
        QMessageBox::critical(this, tr("Editing error!"),
                              tr("Unacceptable instructor name has been entered.\nThe changes will not be accepted."));
        return false;
    }

    if(instructor.getLogin() == QStringLiteral("<login>"))
    {//Логин не корректен!
        QMessageBox::critical(this, tr("Editing error!"),
                              tr("Unacceptable instructor login has been entered.\nThe changes will not be accepted."));
        return false;
    }

    if(instructor.getPassword() == QStringLiteral("<password>"))
    {//Пароль не корректный!
        QMessageBox::critical(this, tr("Editing error!"),
                              tr("Unacceptable instructor password has been entered.\nThe changes will not be accepted."));
        return false;
    }


    QList<Instructor> listInstructors = connectorToServer->getListInstructors();

    for(Instructor exist_instructor : listInstructors)
    {
        if(instructor.getName() == exist_instructor.getName() && instructor.getID() != exist_instructor.getID())
        {//Имя уже существует
            QMessageBox::critical(this, tr("Editing error!"),
                                  tr("An existing instructor name has been entered."));
            return false;
        }

        if(instructor.getLogin() == exist_instructor.getLogin() && instructor.getID() != exist_instructor.getID())
        {//Логин уже существует!
            QMessageBox::critical(this, tr("Editing error!"),
                                  tr("An existing instructor login has been entered.\nThe changes will not be accepted."));
            return false;
        }
    }

    return true;
}

bool EditorInstructors::editInstructor(Instructor instructor, Instructor* instructor_edit)
{
    DialogEditInstructor dlg(this);

    dlg.setInstructor(instructor);

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

            if(! verifyInstructor(*instructor_edit))
            {
                dlg.setInstructor(*instructor_edit);
                continue;
            }

            return true;
        }
        case QDialog::Rejected:
            return false;
        default:
            return false;
        }
    }
}


