#include <QMessageBox>
#include <QProcess>
#include <QFile>
#include "dialogcheckdb.h"
#include "ui_dialogcheckdb.h"

DialogCheckDB::DialogCheckDB(ProviderDBLMS* providerDBLMS, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogCheckDB),
    providerDBLMS(providerDBLMS),
    resDriver(false),
    resUser(false),
    resDB(false)
{
    ui->setupUi(this);

    ui->btnRepare->setObjectName("btnRepare");

    ui->btnRepare->setEnabled(false);

    check();
}

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

void DialogCheckDB::check()
{
    resDriver = false;
    resUser = false;
    resDB = false;

    resDriver = providerDBLMS->checkDriverQPSQLavailable();
    if(resDriver)
    {
        ui->lblDriverRes->setText(tr("Installed"));
        ui->lblDriverResIco->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleGreen.png")));
    }
    else
    {
        ui->lblDriverRes->setText(tr("Not installed"));
        ui->lblDriverResIco->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleRed.png")));
    }

    resUser = providerDBLMS->checkUserLMSexist();
    if(resUser)
    {
        ui->lblUserRes->setText(tr("Exist"));
        ui->lblUserResIco->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleGreen.png")));
    }
    else
    {
        ui->lblUserRes->setText(tr("Not exist"));
        ui->lblUserResIco->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleRed.png")));
    }

    resDB = providerDBLMS->checkDataBaseLMSexist();
    if(resDB)
    {
        ui->lblDBRes->setText(tr("Exist"));
        ui->lblDBResIco->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleGreen.png")));
    }
    else
    {
        ui->lblDBRes->setText(tr("Not exist"));
        ui->lblDBResIco->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleRed.png")));
    }

    if(!resDriver || !resUser || !resDB)
    {
        ui->btnRepare->setEnabled(true);
    }
    else
        ui->btnRepare->setEnabled(false);
}

void DialogCheckDB::on_btnRepare_clicked()
{
    if(!resDriver)
    {
        QMessageBox::critical(this, tr("Error!"), tr("Install PostgreSQL."));
        this->reject();
        return;
    }

    if(!resUser)
    {
        if(!providerDBLMS->createUser())
        {
            check();
            QMessageBox::critical(this, tr("Error!"), tr("Failed to create user!"));            
            this->reject();
            return;
        }
    }

    if(!resDB)
    {
        if(!providerDBLMS->createDB())
        {
            check();
            QMessageBox::critical(this, tr("Error!"), tr("Failed to create Database!"));            
            this->reject();
            return;
        }
    }

    check();

    if(resDriver && resUser && resDB)
    {
        QMessageBox::information(this, tr("Completed!"), tr("The database has been successfully restored!"));
        this->accept();
    }
}
