/*
 *   This file is part of Dianara
 *   Copyright 2012-2019  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(500, 300);

    m_pumpController = pumpController;


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

    m_mailLineEdit = new QLineEdit(this);
    m_mailLineEdit->setClearButtonEnabled(true);
    connect(m_mailLineEdit, &QLineEdit::textEdited,
            this, &EmailChanger::validateFields);

    m_mailRepeatLineEdit = new QLineEdit(this);
    m_mailRepeatLineEdit->setClearButtonEnabled(true);
    connect(m_mailRepeatLineEdit, &QLineEdit::textEdited,
            this, &EmailChanger::validateFields);

    m_passwordLineEdit = new QLineEdit(this);
    m_passwordLineEdit->setEchoMode(QLineEdit::Password);
    connect(m_passwordLineEdit, &QLineEdit::textEdited,
            this, &EmailChanger::validateFields);



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


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

    m_cancelButton = new QPushButton(QIcon::fromTheme("dialog-cancel",
                                                      QIcon(":/images/button-cancel.png")),
                                     tr("&Cancel"),
                                     this);
    connect(m_cancelButton, &QAbstractButton::clicked,
            this, &EmailChanger::cancelDialog);

    m_bottomButtonBox = new QDialogButtonBox(this);
    m_bottomButtonBox->addButton(m_changeButton, QDialogButtonBox::AcceptRole);
    m_bottomButtonBox->addButton(m_cancelButton, QDialogButtonBox::RejectRole);


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



    // Layout
    m_middleLayout = new QFormLayout();
    m_middleLayout->addRow(tr("E-mail Address:"), m_mailLineEdit);
    m_middleLayout->addRow(tr("Again:"),          m_mailRepeatLineEdit);
    m_middleLayout->addRow(tr("Your Password:"),  m_passwordLineEdit);

    m_mainLayout = new QVBoxLayout();
    m_mainLayout->addWidget(m_infoLabel);
    m_mainLayout->addSpacing(8);
    m_mainLayout->addStretch(1);
    m_mainLayout->addLayout(m_middleLayout);
    m_mainLayout->addStretch(1);
    m_mainLayout->addWidget(m_errorsLabel, 2);
    m_mainLayout->addStretch(1);
    m_mainLayout->addSpacing(8);
    m_mainLayout->addWidget(m_bottomButtonBox);
    this->setLayout(m_mainLayout);

    qDebug() << "EmailChanger created";
}


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


void EmailChanger::setCurrentEmail(QString email)
{
    m_currentEmail = email;
    m_mailLineEdit->setText(m_currentEmail);
}



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



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

    const QString mail1 = m_mailLineEdit->text().trimmed();
    const QString mail2 = m_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 (m_passwordLineEdit->text().isEmpty())
    {
        errorString.append("<li>"
                           + tr("Password is empty!")
                           + "</li>");
        validFields = false;
    }

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

    m_errorsLabel->setText(errorString);
    m_changeButton->setEnabled(validFields);
}



void EmailChanger::changeEmail()
{
    m_currentEmail = m_mailLineEdit->text().trimmed();

    m_pumpController->updateUserEmail(m_currentEmail,
                                      m_passwordLineEdit->text());

    this->cancelDialog();
}

void EmailChanger::cancelDialog()
{
    m_mailRepeatLineEdit->clear();
    m_passwordLineEdit->clear();
    m_errorsLabel->clear();

    m_changeButton->setDisabled(true);

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

    this->hide();
}


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


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