//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Authenticate user on login
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void MainWindow::authenticate(std::string user, std::string pss)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("users.db3");
    if (!db.open()) {
        QMessageBox::critical(0, qApp->tr("Cannot open database"),
            qApp->tr("Unable to establish a database connection.\n"
                     "This example needs SQLite support. Please read "
                     "the Qt SQL driver documentation for information how "
                     "to build it.\n\n"
                     "Click Cancel to exit."), QMessageBox::Cancel);
    }

    //look for a username in the users table
    QString queryString = "SELECT * FROM users WHERE username='******'";
    QSqlQuery query(db);
    query.prepare(queryString);

    //if query executes with error display it otherwise move to else
    if( !query.exec() )
      qDebug() << query.lastError();
    else
    {
        //retrieve the query record for processing
        qDebug( "Selected!" );
        query.first();
        QSqlRecord rec = query.record();
        qDebug() << rec.value(0).toString();

        //if record is empty no username was found
        if (rec.value(0).toString() == "")
        {
            invalidDialog("Username not found");
            db.close();
            on_loginButton_clicked();
        }//not in database
        else if(QString::fromStdString(encryption::decrypt(rec.value(1).toString().toStdString(), 29, 41)) != QString::fromStdString(pss))
        {
            //passsword for the found username didn't match record
            invalidDialog("Password doesn't match any on record");
            db.close();
            on_loginButton_clicked();
        }//username found, but password doesn't match
        else
        {
            //all records match so login
            username = user;
            ui->nameLabel->setText(QString::fromStdString(user));
        }
    }
    db.close();
}
void MainWindow::loginDialog()
{
    QDialog dialog(this);
    // Use a layout allowing to have a label next to each field
    QFormLayout form(&dialog);

    // Add some text above the fields
    form.addRow(new QLabel("Please enter credentials:"));

    // Add the lineEdits with their respective labels
    QLineEdit *userEdit = new QLineEdit(&dialog);
    QString userString = QString("Username:"******"Password:"******"Register");
    okButton->setText("Ok");
    cancelButton->setText("Cancel");

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(okButton);
    layout->addWidget(cancelButton);
    layout->addWidget(regButton);

    //QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
    form.addRow(layout);
    QObject::connect(regButton, SIGNAL(clicked()), this, SLOT(registerAccount()));
    QObject::connect(okButton, SIGNAL(clicked()), &dialog, SLOT(accept()));
    QObject::connect(cancelButton, SIGNAL(clicked()), this, SLOT(exitFunction()));

    dialog.setWindowFlags( ( (dialog.windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowCloseButtonHint) );

    // ok button pressed enters the if statement
    // cancel button closes application
    // register button opens register dialog
    if (dialog.exec() == QDialog::Accepted) {
        // If the user didn't dismiss the dialog, do something with the fields
        std::string user = userEdit->text().toStdString();
        std::string pss = passEdit->text().toStdString();
        if (userEdit->text() == "" || passEdit->text() == "")
        {
            invalidDialog("Please enter a valid username or password");
            on_loginButton_clicked();
        }
        else
        {
            authenticate(user, pss);
            enableStatus(true);
        }
    }
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: on_loginButton_clicked(); break;
        case 1: on_bookStorageButton_clicked(); break;
        case 2: on_findBookButton_clicked(); break;
        case 3: on_borrowBookButton_clicked(); break;
        case 4: on_returnBookButton_clicked(); break;
        case 5: on_cardManageButton_clicked(); break;
        case 6: on_actionAbout_Author_triggered(); break;
        case 7: on_actionAbout_Software_triggered(); break;
        default: ;
        }
        _id -= 8;
    }
    return _id;
}
void LoginWin::on_passEntry_returnPressed() {
    on_loginButton_clicked();
}
LoginGroupBox::LoginGroupBox(QWidget *parent):
    QGroupBox(parent),
    messageLabel(new QLabel(this)),
    usernameEdit(new QLineEdit(this)),
    passwordEdit(new QLineEdit(this)),
    loginButton(new QPushButton(this)),
    regButton(new QPushButton(this)),
    headSculp(new QLabel(this)),
    aboutUs(new QLabel(this)),
    regDialog(0),
    pressed(false)
{
    this->setGeometry(0, 0, 400, 280);

    QFont font;
    font.setPointSize(10);

    this->regButton->setFocusPolicy(Qt::ClickFocus);
    this->passwordEdit->setEchoMode(QLineEdit::Password);
    this->aboutUs->setOpenExternalLinks(true);
    this->usernameEdit->setFocus();

    this->usernameEdit->setPlaceholderText("请输入用户名");
    this->passwordEdit->setPlaceholderText("请输入密码");
    this->loginButton->setText("登  陆");
    this->regButton->setText("免费注册");
    this->aboutUs->setText("<style>a{text-decoration: none;}</style><a href=\"http://ssdut153.cn/\">  关于我们");

    QPalette pal = this->regButton->palette();
    pal.setColor(QPalette::ButtonText, QColor(28, 0, 255));

    this->regButton->setPalette(pal);
    this->loginButton->setFont(font);
    this->regButton->setFont(font);
    this->aboutUs->setFont(font);
    this->usernameEdit->setFont(font);
    this->passwordEdit->setFont(font);
    this->messageLabel->setFont(font);

    pal = this->messageLabel->palette();
    pal.setColor(QPalette::WindowText, Qt::red);
    this->messageLabel->setPalette(pal);

    this->messageLabel->setGeometry(109, 80, 192, 32);
    this->usernameEdit->setGeometry(107, 108, 192, 32);
    this->passwordEdit->setGeometry(107, 150, 192, 32);
    this->loginButton->setGeometry(106, 220, 194, 32);
    this->regButton->setGeometry(306, 108, 65, 32);
    this->headSculp->setGeometry(23, 108, 74, 74);
    this->aboutUs->setGeometry(313, 150, 65, 32);

    this->usernameEdit->setStyleSheet("border:2px;");

    this->passwordEdit->setStyleSheet("border:2px;");

    this->regButton->setStyleSheet("QPushButton{background-color:rgba(244,13,100,0);border:0px;}"
                                   "QPushButton:hover{color:white;}"
                                   "QPushButton:focus{border:0px;}");

    QImage head(":/images/photo");
    head.scaled(74, 74, Qt::KeepAspectRatio);
    this->headSculp->setScaledContents(true);
    this->headSculp->setPixmap(QPixmap::fromImage(head));

    this->setTabOrder(this->usernameEdit, this->passwordEdit);
    this->setTabOrder(this->passwordEdit, this->loginButton);
    this->setTabOrder(this->loginButton, this->usernameEdit);

    connect(this->loginButton, SIGNAL(clicked()), this, SLOT(on_loginButton_clicked()));
    connect(this->regButton, SIGNAL(clicked()), this, SLOT(on_regButton_clicked()));
    connect(this->usernameEdit,SIGNAL(textChanged(QString)),this, SLOT(on_usernameEdit_textChanged()));

}