#include <QMessageBox>
#include "editorinstructors.h"
#include "dialogeditinstructor.h"
#include "specialmessagebox.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);

    ui->btnDeleteInstructor->setEnabled(false);
    ui->btnToOrFromArchive->setEnabled(false);
    ui->btnEdit->setEnabled(false);

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

    ui->verticalLayout_1->addWidget(treeWidget);

    this->adminMode = adminMode;

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

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

    waitAnimationWidget->setParent(this);

    authComplited = true;
}

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

void EditorInstructors::closeEvent(QCloseEvent *event)
{

}

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

    instructor.setNeedSetPassword(true);

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

    lastCurrentID = 0;

    return;
}

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

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

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

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

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

            if(SpecialMessageBox(this, SpecialMessageBox::TypeSpecMsgBox::warningYesNo, tr("The deletion will be irrevocable.\nDelete it anyway?")).exec() == QDialog::Accepted)
            {
                waitAnimationWidget->showWithPlay();
                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(ColumnsTreeUsers::clmn_ID).toInt();

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

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

                instructor.setArchived(true);
                waitAnimationWidget->showWithPlay();
                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(ColumnsTreeUsers::clmn_ID).toInt();

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

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

        Instructor instructor_edit;

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

void EditorInstructors::on_btnArchive_clicked()
{
    bool state = ui->btnArchive->isChecked();    
    setArchiveVisible(state);
    if(!state)
    {
        Instructor instructor = connectorToServer->getInstructor(lastCurrentID);
        if(instructor.getID())
        {
            if(instructor.getArchived())
                lastCurrentID = 0;
        }
        else
        {
            lastCurrentID = 0;
        }
    }
    loadInstructorsFromDB();
}

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

    if(current == nullptr)
    {
        ui->btnDeleteInstructor->setEnabled(false);
        ui->btnToOrFromArchive->setEnabled(false);
        ui->btnEdit->setEnabled(false);
        return;
    }

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

        int id = current->text(ColumnsTreeUsers::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);
    }
    else
    {
        ui->btnDeleteInstructor->setEnabled(false);
        ui->btnToOrFromArchive->setEnabled(false);
        ui->btnEdit->setEnabled(false);
    }
}

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

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

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

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


    int user_I = connectorToServer->getIdInstructorByLogin(instructor.getLogin());
    int user_T = connectorToServer->getIdTraineeByLogin(instructor.getLogin());
    if((user_I && (user_I != instructor.getID())) ||  (user_T && (user_T != instructor.getID())))
    {//Логин уже существует!
        SpecialMessageBox(this, SpecialMessageBox::TypeSpecMsgBox::critical, tr("An existing instructor or trainee login has been entered.\nThe changes will not be accepted.")).exec();
        return 0;
    }

    return true;
}

bool EditorInstructors::editInstructor(Instructor instructor, Instructor* instructor_edit)
{
    DialogEditInstructor dlg(adminMode, this);
    dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowContextHelpButtonHint);

    dlg.setInstructor(instructor);

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

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

            if(instructor_edit->getNeedSetPassword())
            {
                //Хэшируем пароль
                instructor_edit->hashingPassword();
                instructor_edit->setNeedSetPassword(false);
            }

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


