+#include <QNetworkAccessManager>
+#include <QNetworkRequest>
+#include <QNetworkReply>
+#include <QUrl>
+#include <QDebug>
+#include <QPixmap>
+#include <QNetworkDiskCache>
+#include <QDesktopServices>
+#include <QTimer>
+#include <QMutex>
+
+#include "mapfetcherqueue.h"
+
+static int MAX_QUEUE = 10;
+
+MapFetcherQueue::MapFetcherQueue(QObject *parent)
+ : QObject(parent)
+ , downloadCount(0)
+{
+ QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
+ diskCache->setCacheDirectory(QDesktopServices::storageLocation(
+ QDesktopServices::CacheLocation));
+ m_manager.setCache(diskCache);
+}
+
+void MapFetcherQueue::fetchMapImage(const QUrl &url)
+{
+ if (url.isEmpty())
+ return;
+
+ if (downloadQueue.isEmpty())
+ QTimer::singleShot(0, this, SLOT(startNextDownload()));
+
+ if (downloadQueue.length() >= MAX_QUEUE) {
+ qDebug() << "removed from queue";
+ deleteCurrent();
+ downloadQueue.dequeue();
+ }
+
+ downloadQueue.enqueue(url);
+ qDebug() << "fetchMapImage() " << url.path();
+}
+
+void MapFetcherQueue::startNextDownload()
+{
+ if (downloadQueue.isEmpty())
+ return;
+
+ QUrl url = downloadQueue.dequeue();
+
+ QNetworkRequest request(url);
+ request.setRawHeader("User-Agent", "Map Test");
+ request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
+ QNetworkRequest::PreferCache);
+
+ currentDownload = m_manager.get(request);
+ connect(currentDownload, SIGNAL(finished()), this, SLOT(downloadFinished()));
+ connect(currentDownload, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
+ connect(currentDownload, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError()));
+}
+
+void MapFetcherQueue::downloadFinished()
+{
+ static int counter = 0;
+ qDebug() << "downloadFinished(): " << counter++;
+
+ deleteCurrent();
+ startNextDownload();
+}
+
+void MapFetcherQueue::deleteCurrent()
+{
+ mutex.lock();
+ if (currentDownload != NULL)
+ currentDownload->deleteLater();
+ mutex.unlock();
+}
+
+void MapFetcherQueue::downloadReadyRead()
+{
+ qDebug() << "downloadReadyRead()" << currentDownload->url().path();
+
+ if (currentDownload->error()) {
+ qDebug() << "ERROR";
+ emit error(currentDownload->errorString());
+ }
+ else {
+ QImage image;
+ QUrl url = currentDownload->url();
+ if (!image.load(currentDownload, 0))
+ image = QImage();
+
+ emit mapImageReceived(url, QPixmap::fromImage(image));
+ }
+}
+
+void MapFetcherQueue::networkError()
+{
+ emit error(currentDownload->errorString());
+}
+
+MapFetcherQueue::~MapFetcherQueue()
+{
+
+}