/*
 *   This file is part of Dianara
 *   Copyright 2012-2016  JanKusanagi JRR <jancoding@gmx.com>
 *
 *   This program 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 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program 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 this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA .
 */

#include "emailchanger.h"


EmailChanger::EmailChanger(QString explanation,
                           PumpController *pumpController,
                           QWidget *parent) : QWidget(parent)
{
    this->setWindowTitle(tr("Change E-mail Address") + " - Dianara");
    this->setWindowIcon(QIcon::fromTheme("view-pim-mail"));
    this->setWindowFlags(Qt::Dialog);
    this->setWindowModality(Qt::WindowModal);
    this->setMinimumSize(400, 300);

    this->pController = pumpController;


    this->infoLabel = new QLabel(explanation + ".", this);
    infoLabel->setWordWrap(true);

    this->mailLineEdit = new QLineEdit(this);
    connect(mailLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(validateFields()));

    this->mailRepeatLineEdit = new QLineEdit(this);
    connect(mailRepeatLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(validateFields()));

    this->passwordLineEdit = new QLineEdit(this);
    passwordLineEdit->setEchoMode(QLineEdit::Password);
    connect(passwordLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(validateFields()));



    this->errorsLabel = new QLabel(this);
    errorsLabel->setAlignment(Qt::AlignCenter);
    errorsLabel->setWordWrap(true);
    QFont errorsFont;
    errorsFont.setPointSize(errorsFont.pointSize() - 1);
    errorsFont.setItalic(true);
    errorsLabel->setFont(errorsFont);


    this->changeButton = new QPushButton(QIcon::fromTheme("document-save",
                                                          QIcon(":/images/button-save.png")),
                                         tr("Change"),
                                         this);
    this->changeButton->setDisabled(true); // Initially disabled
    connect(changeButton, SIGNAL(clicked()),
            this, SLOT(changeEmail()));

    this->cancelButton = new QPushButton(QIcon::fromTheme("dialog-cancel",
                                                          QIcon(":/images/button-cancel.png")),
                                         tr("&Cancel"),
                                         this);
    connect(cancelButton, SIGNAL(clicked()),
            this, SLOT(cancelDialog()));



    // ESC to cancel, too
    cancelAction = new QAction(this);
    cancelAction->setShortcut(QKeySequence(Qt::Key_Escape));
    connect(cancelAction, SIGNAL(triggered()),
            this, SLOT(cancelDialog()));
    this->addAction(cancelAction);



    // Layout
    this->middleLayout = new QFormLayout();
    middleLayout->addRow(tr("E-mail Address:"), mailLineEdit);
    middleLayout->addRow(tr("Again:"),          mailRepeatLineEdit);
    middleLayout->addRow(tr("Your Password:"),  passwordLineEdit);

    this->bottomLayout = new QHBoxLayout();
    bottomLayout->setAlignment(Qt::AlignRight);
    bottomLayout->addWidget(changeButton);
    bottomLayout->addWidget(cancelButton);

    this->mainLayout = new QVBoxLayout();
    mainLayout->addWidget(infoLabel);
    mainLayout->addSpacing(8);
    mainLayout->addStretch(1);
    mainLayout->addLayout(middleLayout);
    mainLayout->addStretch(1);
    mainLayout->addWidget(errorsLabel, 2);
    mainLayout->addStretch(1);
    mainLayout->addSpacing(8);
    mainLayout->addLayout(bottomLayout);
    this->setLayout(mainLayout);

    qDebug() << "EmailChanger created";
}


EmailChanger::~EmailChanger()
{
    qDebug() << "EmailChanger destroyed";
}


void EmailChanger::setCurrentEmail(QString email)
{
    this->currentEmail = email;
    this->mailLineEdit->setText(this->currentEmail);
}



/****************************************************************************/
/******************************** SLOTS *************************************/
/****************************************************************************/



void EmailChanger::validateFields()
{
    bool validFields = true;

    QString mail1 = this->mailLineEdit->text().trimmed();
    QString mail2 = this->mailRepeatLineEdit->text().trimmed();

    QString errorString = "<ul>";

    // Both e-mails must be equal
    if (mail1 != mail2)
    {
        errorString.append("<li>" + tr("E-mail addresses don't match!")
                           + "</li>");
        validFields = false;
    }

    // Password can't be empty
    if (this->passwordLineEdit->text().isEmpty())
    {
        errorString.append("<li>" + tr("Password is empty!")
                           + "</li>");
        validFields = false;
    }

    errorString.append("</ul>");

    this->errorsLabel->setText(errorString);
    this->changeButton->setEnabled(validFields);
}



void EmailChanger::changeEmail()
{
    this->currentEmail = this->mailLineEdit->text().trimmed();

    this->pController->updateUserEmail(this->currentEmail,
                                       this->passwordLineEdit->text());

    this->cancelDialog();
}

void EmailChanger::cancelDialog()
{
    this->mailRepeatLineEdit->clear();
    this->passwordLineEdit->clear();
    this->errorsLabel->clear();

    this->changeButton->setDisabled(true);

    // Ensure good e-mail is set, in case dialog was cancelled with bad value
    this->mailLineEdit->setText(currentEmail);
    this->mailLineEdit->setFocus();

    this->hide();
}


/****************************************************************************/
/****************************** PROTECTED ***********************************/
/****************************************************************************/


void EmailChanger::closeEvent(QCloseEvent *event)
{
    event->ignore();
    this->cancelDialog();
}
