#include "changepasswordform.h"
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QSettings>

ChangePasswordForm::ChangePasswordForm(QWidget *parent) : BaseDlg(parent) {
    resize(240, 160);
    auto vBox = new QVBoxLayout(this);
    auto hBox = new QHBoxLayout();
    auto label = new QLabel(tr("Old password"));
    hBox->addWidget(label);

    fdOld = new QLineEdit();
    fdOld->setEchoMode(QLineEdit::Password);
    fdOld->setMaxLength(16);
    hBox->addWidget(fdOld);
    vBox->addLayout(hBox);

    hBox = new QHBoxLayout();
    auto label_2 = new QLabel(tr("New password"));
    hBox->addWidget(label_2);

    fdNew = new QLineEdit();
    fdNew->setEchoMode(QLineEdit::Password);
    fdNew->setMaxLength(8);
    hBox->addWidget(fdNew);
    vBox->addLayout(hBox);

    hBox = new QHBoxLayout();
    auto label_3 = new QLabel(tr("Repeat again"));
    hBox->addWidget(label_3);

    fdAgn = new QLineEdit();
    fdAgn->setEchoMode(QLineEdit::Password);
    fdAgn->setMaxLength(8);
    hBox->addWidget(fdAgn);
    vBox->addLayout(hBox);

    hBox = new QHBoxLayout();
    auto pushButton_2 = new QPushButton(tr("OK"));
    pushButton_2->setProperty("ssType", "progManageTool");
    hBox->addWidget(pushButton_2);
    connect(pushButton_2, &QPushButton::clicked, this, [this]() {
        QString pwdOld = fdOld->text();
        if(pwdOld.isEmpty()) {
            QMessageBox::warning(this, tr("Tip"), tr("Please input old password"));
            fdOld->setFocus();
            return;
        }
        QSettings settings;
        QString pwdRaw = settings.value("advUiPs").toString();
        QString pwd = pwdRaw.isEmpty() ? "888" : QString::fromUtf8(QByteArray::fromBase64(pwdRaw.toLatin1()));
        if(pwd != pwdOld) {
            QMessageBox::critical(this, tr("Tip"), tr("Old password is wrong"));
            fdOld->setFocus();
            return;
        }
        QString pwdNew = fdNew->text();
        if(pwdNew.length() < 6) {
            QMessageBox::warning(this, tr("Tip"), tr("Please enter a password with more than 6 characters"));
            fdNew->setFocus();
            return;
        }
        QString pwdAgn = fdAgn->text();
        if(pwdAgn != pwdNew) {
            QMessageBox::warning(this, tr("Tip"), tr("The new password is not consistent in two times"));
            fdAgn->setFocus();
            return;
        }
        settings.setValue("advUiPs", QString::fromLatin1(pwdNew.toUtf8().toBase64()));
        QMessageBox::information(this, tr("Tip"), tr("Password changed successfully"));
        accept();
    });

    auto pushButton = new QPushButton(tr("Cancel"));
    pushButton->setProperty("ssType", "progManageTool");
    hBox->addWidget(pushButton);
    connect(pushButton, &QPushButton::clicked, this, &ChangePasswordForm::reject);
    vBox->addLayout(hBox);
}
