#include "mapview_tile_provider_osm.h"

#include <QNetworkReply>
#include <QNetworkRequest>
#include <piqt.h>


MapViewTileProvider_OSM::MapViewTileProvider_OSM() {
	nam = new QNetworkAccessManager();
	PIValueTree p;
	p.addChild(PIValueTree("url", "https://tile.openstreetmap.org"));
	initParameters(p);
}


MapViewTileProvider_OSM::~MapViewTileProvider_OSM() {
	piDeleteSafety(nam);
}


QString MapViewTileProvider_OSM::name() const {
	static QString ret = "OSM";
	return ret;
}


bool MapViewTileProvider_OSM::requestTile(MapViewTypes::TileIndex index) {
	QNetworkRequest req(url + QString("/%1/%2/%3.png").arg(index.z).arg(index.x).arg(index.y));
	req.setHeader(QNetworkRequest::UserAgentHeader, "Qt/5");
	auto * r = nam->get(req);
	if (!r) return false;
	connect(r, &QNetworkReply::finished, this, [this, r, index]() {
		r->deleteLater();
		QPixmap tim;
		if (r->error() != QNetworkReply::NoError) {
			qDebug() << "Error:" << r->error();
		} else {
			QByteArray data = r->readAll();
			if (!data.isEmpty()) {
				tim.loadFromData(data, "png");
			}
		}
		emit tileReady(index, tim);
	});
	return true;
}


QSize MapViewTileProvider_OSM::tileSize() {
	return {256, 256};
}


int MapViewTileProvider_OSM::maximumLevel() const {
	return 19;
}


void MapViewTileProvider_OSM::applyParameters() {
	url = PI2QString(getParameters().childValue("url").toString());
}
