#include "mapview_tile_provider_maptiler.h"

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


MapViewTileProvider_MapTiler::MapViewTileProvider_MapTiler() {
	nam = new QNetworkAccessManager();
	PIValueTree p;
	p.addChild(PIValueTree("url", "https://api.maptiler.com/tiles"));
	p.addChild(PIValueTree("key", ""));
	p.addChild(PIValueTree("tileset", ""));
	initParameters(p);
}


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


QString MapViewTileProvider_MapTiler::name() const {
	static QString ret = "MapTiler";
	return ret;
}


bool MapViewTileProvider_MapTiler::requestTile(MapViewTypes::TileIndex index) {
	QNetworkRequest req(url + QString("/%1/%2/%3/%4.jpg?key=%5").arg(tileset).arg(index.z).arg(index.x).arg(index.y).arg(key));
	req.setHeader(QNetworkRequest::UserAgentHeader, "Qt/5");
	auto * r = nam->get(req);
	if (!r) return false;
	// qDebug() << "Reqst:" << index.z << index.x << index.y << req.url().toString();
	connect(r, &QNetworkReply::finished, this, [this, r, index]() {
		r->deleteLater();
		QPixmap tim;
		if (r->error() != QNetworkReply::NoError) {
			if (r->error() == QNetworkReply::ContentAccessDenied) {
				qDebug() << "Error:" << index.z << index.x << index.y << r->error();
				return;
			}
			qDebug() << "Retry:" << index.z << index.x << index.y << r->error();
			QTimer::singleShot(500, this, [this, index] { requestTile(index); });
			return;
		} else {
			QByteArray data = r->readAll();
			if (!data.isEmpty()) {
				tim.loadFromData(data, "jpg");
				// qDebug() << "Ready:" << index.z << index.x << index.y;
			}
		}
		tileReady(index, tim);
	});
	return true;
}


QSize MapViewTileProvider_MapTiler::tileSize() {
	return {512, 512};
}


QString MapViewTileProvider_MapTiler::cacheDir() const {
	return name() + "/" + tileset;
}


int MapViewTileProvider_MapTiler::maximumLevel() const {
	return 20;
}


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