//
// Created by Krad on 2021/11/11.
//

#include <QVBoxLayout>
#include <QLabel>
#include <QtWidgets/QLineEdit>
#include "models/User.h"
#include "log/UserOperationLog.h"
#include "ChangePasswordFormDialog.h"

ChangePasswordFormDialog::ChangePasswordFormDialog(QWidget* parent, Qt::WindowFlags f) : GUIFormBaseDialog(parent, f) {
	QVBoxLayout* layout = new QVBoxLayout(formWidget);
	layout->setSpacing(10);
	// add title
	QLabel* lbl_title = new QLabel(this);
	lbl_title->setAlignment(Qt::AlignCenter);
	lbl_title->setText(tr("Change Password"));
	lbl_title->setObjectName("title");
	layout->addWidget(lbl_title);

	//add old password
	QLabel* lbl_Old = new QLabel(this);
	lbl_Old->setText(tr("Current Password"));
	pwd = new QLineEdit(this);
	pwd->setEchoMode(QLineEdit::Password);
	layout->addWidget(lbl_Old);
	layout->addWidget(pwd);
	QLabel* lbl_endline1 = new QLabel(this);
	lbl_endline1->setObjectName("endline");
	layout->addWidget(lbl_endline1);

	//add new password
	QLabel* lbl_New = new QLabel(this);
	lbl_New->setText(tr("New Password"));
	new_pwd = new QLineEdit(this);
	new_pwd->setEchoMode(QLineEdit::Password);
	layout->addWidget(lbl_New);
	layout->addWidget(new_pwd);
	QLabel* lbl_endline2 = new QLabel(this);
	lbl_endline2->setObjectName("endline");
	layout->addWidget(lbl_endline2);

	//add confirm password
	QLabel* lbl_Confirm = new QLabel(this);
	lbl_Confirm->setText(tr("Confirm Password"));
	confirm_pwd = new QLineEdit(this);
	confirm_pwd->setEchoMode(QLineEdit::Password);
	layout->addWidget(lbl_Confirm);
	layout->addWidget(confirm_pwd);
	QLabel* lbl_endline3 = new QLabel(this);
	lbl_endline3->setObjectName("endline");
	layout->addWidget(lbl_endline3);

	lbl_error = new QLabel(this);
	lbl_error->setObjectName("warn");
	layout->addWidget(lbl_error);
}

ChangePasswordFormDialog::~ChangePasswordFormDialog() {

}

bool ChangePasswordFormDialog::updateReferenceData() {
	if (pwd->text().isEmpty())
	{
		lbl_error->setText(tr("Please enter your old password!"));
		return false;
	}
	if (new_pwd->text().length() < 6) {
		lbl_error->setText(tr("New password should at least 6 characters!"));
		return false;
	}
	QString encryptPwd = User::getEncryptedPassword(pwd->text());
	if (encryptPwd != User::Current()->getPassword())
	{
		lbl_error->setText(tr("Wrong password!"));
		return false;
	}
	if (new_pwd->text() != confirm_pwd->text())
	{
		lbl_error->setText(tr("Your new password does not match!"));
		return false;
	}
	User::Current()->setPassword(User::getEncryptedPassword(new_pwd->text()));
	if (!User::Current()->submitChange()) {
		lbl_error->setText(tr("Database update error!"));
		User::Current()->restorePassword(encryptPwd);
		return false;
	}
	LOG_USER_OPERATION(ChangePassword);
	return true;
}
