#include <QMessageBox>
#include "instructorsandtraineeswidget.h"
#include "ui_instructorsandtraineeswidget.h"
#include "dialogauthorizationinstructor.h"
#include "doctaskswidget.h"

InstructorsAndTraineesWidget::InstructorsAndTraineesWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::InstructorsAndTraineesWidget),
    dbLMS(nullptr),
    viewerTrainees(nullptr),
    viewerInstructors(nullptr),
    adminMode(false),
    loginInstructorLoggedInLocal(QStringLiteral(""))
{
    ui->setupUi(this);

    dbLMS = new InterfaceDataBaseLMS(this);

    connect(this, &InstructorsAndTraineesWidget::signal_LanguageChanged, dbLMS, &InterfaceDataBaseLMS::slot_LanguageChanged);

    viewerTrainees = new ViewerTrainees(dbLMS);
    viewerInstructors = new ViewerInstructors(dbLMS);

    connect(this, &InstructorsAndTraineesWidget::signal_NeedUpdateUI, viewerTrainees, &ViewerTrainees::slot_NeedUpdateUI);
    connect(this, &InstructorsAndTraineesWidget::signal_NeedUpdateUI, viewerInstructors, &ViewerInstructors::slot_NeedUpdateUI);

    connect(viewerInstructors, &ViewerInstructors::signal_BlockAutorization, this, &InstructorsAndTraineesWidget::signal_BlockAutorization);
    connect(viewerTrainees, &ViewerTrainees::signal_BlockAutorization, this, &InstructorsAndTraineesWidget::signal_BlockAutorization);

    connect(viewerTrainees, &ViewerTrainees::signal_traineeSelected, this, &InstructorsAndTraineesWidget::signal_traineeSelected);
    connect(this, &InstructorsAndTraineesWidget::signal_tabMessengerChanged, viewerTrainees, &ViewerTrainees::slot_tabMessengerChanged);

    ui->verticalLayout->addWidget(viewerTrainees);
    ui->verticalLayout->addWidget(viewerInstructors);

    viewerTrainees->setMinimumSize(1600, 600);
    viewerInstructors->setMinimumSize(1600, 300);

    ui->btnAuthorizationInstructor->setEnabled(false);

    //ui->btnConnectionToDB->click();
}

InstructorsAndTraineesWidget::~InstructorsAndTraineesWidget()
{
    if(authorizationIsCompleted())
        deAuthorizationInstructor(loginInstructorLoggedInLocal);

    if(dbLMS->DBisConnected())
    {
        dbLMS->deAuthorizationAllInstructors();
        dbLMS->deAuthorizationAllTrainees();

        dbLMS->DisConnectionFromDB();
    }

    delete viewerInstructors;
    delete viewerTrainees;
    delete dbLMS;
    delete ui;
}

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

        if(ui->btnAuthorizationInstructor->isChecked())
            ui->btnAuthorizationInstructor->setText(tr("Deauthorization Instructor"));
        else
            ui->btnAuthorizationInstructor->setText(tr("Authorization Instructor"));

        if(ui->btnConnectionToDB->isChecked())
            ui->btnConnectionToDB->setText(tr("Disconnection DB"));
        else
            ui->btnConnectionToDB->setText(tr("Connection DB"));

        updateLabelLoggedInInstructor();
    }
}

void InstructorsAndTraineesWidget::slot_LanguageChanged(QString language)
{
    qtLanguageTranslator.load(QString(QStringLiteral("translations/InstructorsAndTraineesWidget_")) + language, QStringLiteral("."));
    qApp->installTranslator(&qtLanguageTranslator);

    Q_EMIT signal_LanguageChanged(language);
}

bool InstructorsAndTraineesWidget::authorizationInstructorLocal(QWidget* parent)
{
    DialogAuthorizationInstructor dlg(parent);
    dlg.setWindowTitle(tr("Instructor authorization"));

    do
    {
        switch( dlg.exec() )
        {
        case QDialog::Accepted:
        {
            QString login = dlg.getLogin();
            QString password = dlg.getPassword();

            if(authorizationInstructor(login, password))
            {
                loginInstructorLoggedInLocal = login;

                if(login == QStringLiteral("admin"))
                    adminMode = true;
                else
                    adminMode = false;

                viewerInstructors->setAdminMode(adminMode);
                viewerTrainees->setAdminMode(adminMode);
                viewerInstructors->setAuthComplited(true);
                viewerTrainees->setAuthComplited(true);

                //Q_EMIT signal_NeedUpdateUI(true, true);

                QMessageBox::information(parent, tr("Instructor authorization"), tr("Successfully!"));

                return true;
            }
            else
                QMessageBox::warning(parent, tr("Instructor authorization"), tr("Invalid login or password!"));

            break;
        }
        case QDialog::Rejected:
            return false;
        default:
            return false;
        }
    }
    while(true);

    return false;
}

bool InstructorsAndTraineesWidget::authorizationIsCompleted()
{
    if(loginInstructorLoggedInLocal == QStringLiteral(""))
        return false;
    else
        return true;
}

bool InstructorsAndTraineesWidget::authorizationTrainee(QString login, QString password, QString classroom_name, QString computer_name)
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return false;
    }

    Q_EMIT signal_BlockAutorization(true);

    bool res = dbLMS->AuthorizationTrainee(login, password, classroom_name, computer_name);

    Q_EMIT signal_BlockAutorization(false);

    if(res)
        Q_EMIT signal_NeedUpdateUI(false, true);

     mtxAccess.unlock();
     return res;
}

bool InstructorsAndTraineesWidget::deAuthorizationTrainee(QString login)
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return false;
    }

    Q_EMIT signal_BlockAutorization(true);

    bool res = dbLMS->deAuthorizationTrainee(login);

    Q_EMIT signal_BlockAutorization(false);

    if(res)
        Q_EMIT signal_NeedUpdateUI(false, true);

    mtxAccess.unlock();
    return res;
}

QString InstructorsAndTraineesWidget::getNameTraineeByLogin(QString login)
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return QStringLiteral("");
    }

    QString res =  dbLMS->getNameTraineeByLogin(login);

    mtxAccess.unlock();
    return res;
}

bool InstructorsAndTraineesWidget::authorizationInstructor(QString login, QString password)
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return false;
    }

    Q_EMIT signal_BlockAutorization(true);

    bool res = dbLMS->AuthorizationInstructor(login, password);

    Q_EMIT signal_BlockAutorization(false);

    if(res)
        Q_EMIT signal_NeedUpdateUI(true, false);

    mtxAccess.unlock();
    return res;
}

bool InstructorsAndTraineesWidget::deAuthorizationInstructor(QString login)
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return false;
    }

    Q_EMIT signal_BlockAutorization(true);

    bool res = dbLMS->deAuthorizationInstructor(login);

    Q_EMIT signal_BlockAutorization(false);

    if(res)
    {
        if(loginInstructorLoggedInLocal == login)
        {
            loginInstructorLoggedInLocal = QStringLiteral("");
            adminMode = false;

            viewerInstructors->setAdminMode(adminMode);
            viewerTrainees->setAdminMode(adminMode);
            viewerInstructors->setAuthComplited(false);
            viewerTrainees->setAuthComplited(false);

            Q_EMIT signal_NeedUpdateUI(true, false);
        }
        else
            Q_EMIT signal_NeedUpdateUI(true, false);
    }

    mtxAccess.unlock();
    return res;
}

QString InstructorsAndTraineesWidget::getNameInstructorByLogin(QString login)
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return QStringLiteral("");
    }

    QString res = dbLMS->getNameInstructorByLogin(login);

    mtxAccess.unlock();
    return res;
}

QString InstructorsAndTraineesWidget::getMainInstructorName()
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return QStringLiteral("");
    }

    QString res = dbLMS->getNameInstructorByLogin(loginInstructorLoggedInLocal);

    mtxAccess.unlock();
    return res;
}
/*
QList<Trainee> InstructorsAndTraineesWidget::getListTrainees()
{
    return dbLMS->getListTrainees();
}
*/

void InstructorsAndTraineesWidget::on_btnConnectionToDB_clicked()
{
    bool stateIsChecked = ui->btnConnectionToDB->isChecked();

    if(stateIsChecked)
    {//Подключение к БД
         mtxAccess.lock();
        if(! dbLMS->DBisConnected())
        {
            if(dbLMS->ConnectionToDB())
            {
                ui->btnConnectionToDB->setText(tr("Disconnection DB"));
                ui->btnAuthorizationInstructor->setEnabled(true);

                ui->lblDBisConnected->setPixmap(QPixmap(QStringLiteral(":/icons/circleGreen.png")));

                Q_EMIT signal_NeedUpdateUI(true, true);

                Q_EMIT signal_BlockAutorization(false);

                Q_EMIT signal_InitMessanger(dbLMS->getListTrainees());
            }
        }
        mtxAccess.unlock();
    }
    else
    {//Отключение от БД
        bool stateIsCheckedAuthorization = ui->btnAuthorizationInstructor->isChecked();
        if(stateIsCheckedAuthorization)
            ui->btnAuthorizationInstructor->click();

         mtxAccess.lock();
        if(dbLMS->DBisConnected())
        {
            Q_EMIT signal_BlockAutorization(true);

            dbLMS->DisConnectionFromDB();

            ui->btnConnectionToDB->setText(tr("Connection DB"));
            ui->btnAuthorizationInstructor->setEnabled(false);

            ui->lblDBisConnected->setPixmap(QPixmap(QStringLiteral(":/icons/circleGray.png")));

            Q_EMIT signal_NeedUpdateUI(true, true);
        }
        mtxAccess.unlock();
    }    
}

void InstructorsAndTraineesWidget::on_btnAuthorizationInstructor_clicked()
{
    bool stateIsChecked = ui->btnAuthorizationInstructor->isChecked();

    if(stateIsChecked)
    {//Авторизация Инструктора локальная (Администратора)
        if(authorizationInstructorLocal(this))
        {
            ui->btnAuthorizationInstructor->setText(tr("Deauthorization Instructor"));

            updateLabelLoggedInInstructor();

            Q_EMIT signal_NeedUpdateUI(true, true);
        }
        else
            ui->btnAuthorizationInstructor->setChecked(false);
    }
    else
    {//ДеАвторизация Инструктора локальная (Администратора)
        if(authorizationIsCompleted())
        {
            if(deAuthorizationInstructor(loginInstructorLoggedInLocal))
            {
                ui->btnAuthorizationInstructor->setText(tr("Authorization Instructor"));

                updateLabelLoggedInInstructor();

                Q_EMIT signal_NeedUpdateUI(true, true);
            }
        }
    }
}

void InstructorsAndTraineesWidget::updateLabelLoggedInInstructor()
{
    mtxAccess.lock();

    if(! dbLMS->DBisConnected())
    {
        mtxAccess.unlock();
        return;
    }

    if(authorizationIsCompleted())
    {
        QString nameLoggedInInstructor = QString("%1 (%2)").arg(
                    dbLMS->getNameInstructorByLogin(loginInstructorLoggedInLocal), loginInstructorLoggedInLocal);
        ui->lblLoggedInInstructor->setText(nameLoggedInInstructor);
        if(loginInstructorLoggedInLocal == QStringLiteral("admin"))
            ui->lblLoggedIn->setPixmap(QPixmap(QStringLiteral(":/icons/admin.png")));
        else
            ui->lblLoggedIn->setPixmap(QPixmap(QStringLiteral(":/icons/instructor.png")));
    }
    else
    {
        ui->lblLoggedInInstructor->setText(tr("none"));
        ui->lblLoggedIn->setPixmap(QPixmap(QStringLiteral(":/icons/circleGray.png")));
    }

    mtxAccess.unlock();
}

void InstructorsAndTraineesWidget::on_btnDocTasks_clicked()
{
    DocTasksWidget docTasks(this);
    QDialog* dialog = new QDialog(this);
    QHBoxLayout *layout = new QHBoxLayout(dialog);
    layout->addWidget(&docTasks);
    dialog->setWindowTitle(tr("Doc tasks"));
    dialog->setMinimumSize(1200, 800);
    dialog->exec();
}

void InstructorsAndTraineesWidget::on_toolButton_clicked()
{
    viewerTrainees->updateMyStyleSheet();
    viewerInstructors->updateMyStyleSheet();
}
