+/***************************************************************************
+ * Copyright (C) 2009 by Lassi Väätämöinen *
+ * lassi.vaatamoinen@ixonos.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., *
+ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
+ ***************************************************************************/
+
+#include <QDebug>
+
+#include "DownloadManager.h"
+
+
+DownloadManager::DownloadManager(QObject *parent) :
+ QObject(parent) // Superclass construct
+{
+}
+
+DownloadManager::DownloadManager(QUrl url, QString outfile, QObject *parent) :
+ QObject(parent), // Superclass construct
+ url_(url),
+ filepath_(outfile),
+ file_(QString(outfile))
+{
+ file_.open(QIODevice::WriteOnly);
+}
+
+
+DownloadManager::~DownloadManager()
+{
+ file_.close();
+ delete reply_; reply_ = NULL;
+}
+
+
+void DownloadManager::start()
+{
+ reply_ = manager_.get(QNetworkRequest(url_));
+
+ connect(reply_, SIGNAL(readyRead()), this, SLOT(on_readyRead()));
+ connect(reply_, SIGNAL(downloadProgress (qint64 , qint64)), SLOT(on_downloadProgress(qint64, qint64)));
+ connect(reply_, SIGNAL(finished()), this, SLOT(on_replyFinished()));
+}
+
+
+void DownloadManager::on_readyRead()
+{
+ //qDebug() << "on_readyRead()";
+ WriteToFile();
+}
+
+void DownloadManager::on_downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
+{
+ static double last = 0;
+
+ double prog = static_cast<double>(bytesReceived) / static_cast<double>(bytesTotal);
+ if ((prog-last) >= 0.01) {
+ last = prog;
+ emit progress(static_cast<int>(100*prog));
+ } else if (bytesReceived == bytesTotal) {
+ emit progress(100);
+ }
+
+}
+
+void DownloadManager::on_replyFinished()
+{
+ WriteToFile();
+ file_.close();
+ emit finished(filepath_);
+}
+
+
+void DownloadManager::WriteToFile()
+{
+ QByteArray readData = reply_->readAll();
+
+ if (readData.isEmpty()) {
+ qDebug() << "on_replyFinished(): No data available for reading";
+ } else {
+ file_.write(readData);
+ /// @todo check file_.error()
+ }
+}