/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Authors: Reinhard Pointner
 *			 Peter Hofer <ph@desktopbsd.net>
 *			 (C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

/* DesktopBSD */
#include <dialogs.h>
#include <dbsdglobal.h>

/* Users */
#include <user.h>

void frmChangePasswd::init() {
	/* Initialize Graphics */
	user = NULL;

	/* Set system max password length */
	editNewPw->setMaxLength(_PASSWORD_LEN);
	editConfPw->setMaxLength(_PASSWORD_LEN);

	DBSDIconLoader  *iloader = DBSDGlobal::getIconLoader();
	pixIcon->setPixmap(iloader->loadIcon("password", DBSDIconLoader::Size32x32));
	btnChange->setIconSet(iloader->loadIcon("button_ok", DBSDIconLoader::Button));
	btnCancel->setIconSet(iloader->loadIcon("button_cancel", DBSDIconLoader::Button));
}


void frmChangePasswd::polish() {
	/* A user must be specified when
	 * the dialog is about to show.
	 */
	if(user == NULL)
		qDebug("frmChangePasswd: No user specified when polish() was called.");

	QDialog::polish();
}


void  frmChangePasswd::change() {
	if(user == NULL)
		return;

	QString  newpwd = editNewPw->text(),
							confirm = editConfPw->text();

	bool	cancel = false;

	if(cancel = (newpwd != confirm))
		Dialogs::warnDlg(tr("Passwords don't match!"));
	else if(newpwd.length() < 6)
		cancel = !Dialogs::question(tr("This password is shorter than 6 characters.\n"
												 "\n"
												 "Do you really want to use this password?"));

	if(cancel) {
		editNewPw->clear();
		editConfPw->clear();
		editNewPw->setFocus();
	} else {
		if(user->setPassword(newpwd))
			accept();
		else
			Dialogs::warnDlg(tr("An error occured when setting the password."));
	}
}


void  frmChangePasswd::setUser(const User& user) {
	this->user = new User(user);
	setCaption(tr("%1's password").arg(user.getUsername()));
}


void  frmChangePasswd::destroy() {
	delete  user;
}


/** Disables and enables the "Cancel" button. */
void frmChangePasswd::setCancelEnabled(bool enabled) {
	btnCancel->setEnabled(enabled);
}


/** Special implementation of the reject() method
  * to only allow to cancel the dialog if the cancel
  * button is enabled.
  *
  * @see setCancelEnabled
  */
void frmChangePasswd::reject() {
	if(btnCancel->isEnabled())
		QDialog::reject();
}
