/*
  Copyright 2010-2012 Grégory Soutadé

  This file is part of KissCount.

  KissCount is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  KissCount is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with KissCount.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "PasswordDialog.hpp"
#include <QMessageBox>
#include <QLabel>

PasswordDialog::PasswordDialog(KissCount* kiss, wxUI *parent) : QDialog(0, Qt::Dialog), _kiss(kiss), _wxUI(parent)
{
    QGridLayout *gridBagSizer;

    gridBagSizer = new QGridLayout(this);

    setWindowTitle(_("Change password"));
    setModal(true);

    gridBagSizer->addWidget(new QLabel(_("Old password")), 0, 0);
    _oldPassword = new QLineEdit();
    gridBagSizer->addWidget(_oldPassword, 0, 1);

    gridBagSizer->addWidget(new QLabel(_("New password")), 1, 0);
    _newPassword = new QLineEdit();
    gridBagSizer->addWidget(_newPassword, 1, 1);

    gridBagSizer->addWidget(new QLabel(_("Confirm password")), 2, 0);
    _confirmPassword = new QLineEdit();
    gridBagSizer->addWidget(_confirmPassword, 2, 1);

    _oldPassword->setEchoMode(QLineEdit::Password);
    _newPassword->setEchoMode(QLineEdit::Password);
    _confirmPassword->setEchoMode(QLineEdit::Password);

    QPushButton* ok = new QPushButton(_("OK"));
    QPushButton* cancel = new QPushButton(_("Cancel"));
    gridBagSizer->addWidget(ok, 4, 1);
    gridBagSizer->addWidget(cancel, 4, 2);

    connect(ok, SIGNAL(clicked()), this, SLOT(OnOK()));
    connect(cancel, SIGNAL(clicked()), this, SLOT(OnCancel()));
}

void PasswordDialog::OnOK()
{
    User* user = _kiss->GetUser();

    if (!_kiss->IsValidUser(user->_name, _oldPassword->text()))
    {
        QMessageBox::critical(0, _("Error"), _("Invalid old password"));
        return;
    }

    if (_newPassword->text() != _confirmPassword->text())
    {
        QMessageBox::critical(0, _("Error"), _("Please retype new password"));
        return;
    }

    _kiss->ChangePassword(_newPassword->text());

    QMessageBox::information(0, "KissCount", _("Password changed"));

    close();
}

void PasswordDialog::OnCancel()
{
    close();
}