/***************************** LICENSE START ***********************************

 Copyright 2013 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQMailDialog.h"

#include <QApplication>
#include <QCompleter>
#include <QDialogButtonBox>
#include <QFile>
#include <QFileInfo>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QSettings>
#include <QTextStream>
#include <QVBoxLayout>

#include "MvQMethods.h"
#include "MvQTheme.h"

MvQMailDialog::MvQMailDialog(const std::string& fAttach, const std::string& fAttachInfo)
{
    setWindowTitle(tr("Send icons in mail - Metview"));

    QApplication::setWindowIcon(QIcon(MvQTheme::logo()));

    auto* vb = new QVBoxLayout(this);

    auto* grid = new QGridLayout();
    vb->addLayout(grid);

    auto* label = new QLabel(tr("To:"), this);
    toLe_ = new QLineEdit(this);
    grid->addWidget(label, 0, 0);
    grid->addWidget(toLe_, 0, 1);

    label = new QLabel(tr("Cc:"), this);
    ccLe_ = new QLineEdit(this);
    grid->addWidget(label, 1, 0);
    grid->addWidget(ccLe_, 1, 1);

    label = new QLabel(tr("Subject:"), this);
    subjLe_ = new QLineEdit(tr("Metview icons"), this);
    grid->addWidget(label, 2, 0);
    grid->addWidget(subjLe_, 2, 1);

    msgTe_ = new QPlainTextEdit(this);
    msgTe_->setProperty("mail", "1");
    vb->addWidget(msgTe_, 1);

    //------------------------
    // List of files
    //------------------------

    QStringList items;
    QFile file(fAttachInfo.c_str());
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream its(&file);
        while (!its.atEnd())
            items << its.readLine();

        QFileInfo info(fAttach.c_str());

        label = new QLabel(tr("This is the list of icons (and their descriptor files) you are about to send as a <b>tar.gz</b> attachment (<b>") +
                               formatFileSize(info.size()) + "</b> in total).",
                           this);
        label->setWordWrap(true);
        vb->addWidget(label);

        auto* itemTe = new QPlainTextEdit(this);
        itemTe->setReadOnly(true);
        itemTe->setLineWrapMode(QPlainTextEdit::NoWrap);

        QFont font("Courier");
        font.setStyleHint(QFont::TypeWriter);
        font.setFixedPitch(true);
        itemTe->setFont(font);
        vb->addWidget(itemTe);

        QString txt;
        foreach (QString str, items) {
            txt += str + "\n";
        }
        itemTe->setPlainText(txt);
    }

    //-----------------------
    // Buttons
    //-----------------------

    auto* bb = new QDialogButtonBox(this);
    bb->addButton(new QPushButton(QPixmap(":/mail/mail_send.svg"), tr("Send"), this),
                  QDialogButtonBox::AcceptRole);

    // bb->addButton(QDialogButtonBox::Ok);
    bb->addButton(QDialogButtonBox::Cancel);
    vb->addWidget(bb);

    connect(bb, SIGNAL(accepted()),
            this, SLOT(accept()));

    connect(bb, SIGNAL(rejected()),
            this, SLOT(reject()));


    readSettings();
}

void MvQMailDialog::accept()
{
    if (to().isEmpty()) {
        QMessageBox::critical(this, tr("No address specified"),
                              tr("Cannot send email!<br> No <b>recepient</b> is specified!"));
        return;
    }
    else {
        writeSettings();
        QDialog::accept();
    }
}

void MvQMailDialog::reject()
{
    writeSettings();
    QDialog::reject();
}

void MvQMailDialog::closeEvent(QCloseEvent* event)
{
    writeSettings();
    event->accept();
}

QString MvQMailDialog::to() const
{
    return toLe_->text();
}

QString MvQMailDialog::cc() const
{
    return ccLe_->text();
}

QString MvQMailDialog::subject() const
{
    return subjLe_->text();
}

QString MvQMailDialog::message() const
{
    return msgTe_->toPlainText();
}

QString MvQMailDialog::formatFileSize(qint64 size) const
{
    QString col;
    if (size < 1000000)
        col = "green";
    else if (size < 5000000)
        col = "orange";
    else
        col = "red";

    QString str;
    if (size < 1024)
        str = QString::number(size) + " B";
    else if (size < 1024 * 1024)
        str = QString::number(size / 1024) + " KB";
    else if (size < 1024 * 1024 * 1024)
        str = QString::number(size / (1024 * 1024)) + " MB";
    else
        str = QString::number(size / (1024 * 1024 * 1024)) + " GB";

    return "<font color=\"" + col + "\">" + str + "</font>";
}

void MvQMailDialog::readSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-MvQMailDialog");

    settings.beginGroup("main");
    if (settings.contains("size")) {
        resize(settings.value("size").toSize());
    }
    else {
        resize(QSize(500, 420));
    }

    toLe_->setText(settings.value("to").toString());
    ccLe_->setText(settings.value("cc").toString());
    toLst_ = settings.value("toLst").toStringList();
    if (toLe_->completer() == nullptr) {
        if (toLst_.count() > 0)
            toLe_->setCompleter(new QCompleter(toLst_, this));
    }

    settings.endGroup();
}

void MvQMailDialog::writeSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-MvQMailDialog");

    settings.clear();

    settings.beginGroup("main");
    settings.setValue("size", size());
    settings.setValue("to", to());
    settings.setValue("cc", cc());

    if (!to().isEmpty()) {
        toLst_.prepend(to());
        toLst_.removeDuplicates();

        while (toLst_.count() > 20)
            toLst_.pop_back();
    }

    settings.setValue("toLst", toLst_);

    settings.endGroup();
}
