/*
 *   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 "downloadwidget.h"


DownloadWidget::DownloadWidget(QString fileUrl,
                               QString suggestedFN,
                               PumpController *pumpController,
                               QWidget *parent) : QFrame(parent)
{
    this->pController = pumpController;
    this->setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
    this->downloading = false;

    this->fileUrl = fileUrl;
    this->suggestedFilename = suggestedFN;

    QFont infoFont;
    infoFont.setPointSize(infoFont.pointSize() - 1);

    infoLabel = new QLabel(this);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setFont(infoFont);
    infoLabel->hide();

    downloadButton = new QPushButton(QIcon::fromTheme("download",
                                                      QIcon(":/images/button-download.png")),
                                     tr("Download"),
                                     this);
    downloadButton->setToolTip("<b></b>"
                               + tr("Save the attached file to your folders"));
    downloadButton->setFlat(true);
    connect(downloadButton, SIGNAL(clicked()),
            this, SLOT(downloadAttachment()));


    progressBar = new QProgressBar(this);
    progressBar->setValue(0);
    progressBar->hide();       // Initially hidden

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


    mainLayout = new QHBoxLayout();
    mainLayout->addWidget(infoLabel);
    mainLayout->addWidget(downloadButton);
    mainLayout->addWidget(progressBar);
    mainLayout->addWidget(cancelButton);
    this->setLayout(mainLayout);

    qDebug() << "DownloadWidget created";
}

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


void DownloadWidget::resetWidget()
{
    this->downloadButton->show();

    this->progressBar->hide();
    this->cancelButton->hide();

    networkReply->disconnect();
    networkReply->deleteLater();

    disconnect(pController, SIGNAL(downloadCompleted(QString)),
               this, SLOT(completeDownload(QString)));
    disconnect(pController, SIGNAL(downloadFailed(QString)),
               this, SLOT(onDownloadFailed(QString)));

    downloadedFile.close();

    this->downloading = false;
}



////////////////////////////////////////////////////////////////////////////
////////////////////////////////// SLOTS ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////


void DownloadWidget::downloadAttachment()
{
    if (downloading)
    {
        qDebug() << "Already downloading!!";
        return;
    }

    QString filename;
    filename = QFileDialog::getSaveFileName(this, tr("Save File As..."),
                                            QDir::homePath() + "/"
                                            + suggestedFilename,
                                            tr("All files") + " (*)");

    if (!filename.isEmpty())
    {
        this->downloading = true;

        this->infoLabel->show();
        this->downloadButton->hide();

        this->progressBar->show();
        this->progressBar->setValue(0);
        this->progressBar->setToolTip("");

        this->cancelButton->show();

        this->downloadedFile.setFileName(filename);
        downloadedFile.open(QIODevice::WriteOnly);

        networkReply = this->pController->getMedia(fileUrl);
        connect(networkReply, SIGNAL(readyRead()),
                this, SLOT(storeFileData()));
        connect(networkReply, SIGNAL(downloadProgress(qint64,qint64)),
                this, SLOT(updateProgressBar(qint64,qint64)));

        connect(pController, SIGNAL(downloadCompleted(QString)),
                this, SLOT(completeDownload(QString)));
        connect(pController, SIGNAL(downloadFailed(QString)),
                this, SLOT(onDownloadFailed(QString)));
    }
}


void DownloadWidget::cancelDownload()
{
    int confirmation = QMessageBox::question(this, tr("Abort download?"),
                                             tr("Do you want to stop "
                                                "downloading the attached "
                                                "file?"),
                                             tr("&Yes, stop"),
                                             tr("&No, continue"),
                                             "", 1, 1);

    if (confirmation == 0)
    {
        this->networkReply->abort();

        infoLabel->setText(tr("Download aborted"));
        resetWidget();
    }
    else
    {
        qDebug() << "Confirmation cancelled, NOT stopping download";
    }
}


void DownloadWidget::completeDownload(QString url)
{
    if (url == this->fileUrl) // Ensure completed download is this download
    {
        infoLabel->setText(tr("Download completed"));
        resetWidget();
    }
}

void DownloadWidget::onDownloadFailed(QString url)
{
    if (url == this->fileUrl) // Ensure failed download is this download
    {
        infoLabel->setText(tr("Download failed"));
        qDebug() << "Download FAILED!" << url;

        resetWidget();
    }
}


void DownloadWidget::storeFileData()
{
    QByteArray data = networkReply->readAll();
    this->downloadedFile.write(data);
}


void DownloadWidget::updateProgressBar(qint64 received, qint64 total)
{
    this->progressBar->setRange(0, total);
    this->progressBar->setValue(received);

    this->infoLabel->setText(tr("Downloading %1 KiB...")
                             .arg(QLocale::system().toString(total / 1024)));

    QString downloadedTooltip = tr("%1 KiB downloaded")
                                .arg(QLocale::system().toString(received / 1024));
    this->infoLabel->setToolTip(downloadedTooltip);
    this->progressBar->setToolTip(downloadedTooltip);
}
