#include "mainwindow.h"

#include "mapitemellipse.h"
#include "mapitemgeopolygon.h"
#include "mapitemgeopolyline.h"
#include "mapitemimage.h"
#include "mapitempolygon.h"
#include "mapitemtext.h"
#include "mapview_tile_provider_osm.h"
#include "osm_geocoding.h"
#include "piliterals_time.h"
#include "piqt.h"
#include "qad_locations.h"

#include <QDateTime>
#include <QDebug>
#include <QFileDialog>
#include <QTimer>
#include <math.h>

MainWindow::MainWindow(QWidget * parent): EMainWindow(parent), Ui::MainWindow() {
	setupUi(this);
	map->setTileObsoleteTime((5_d).toSeconds());
	map->setTileProvider(new MapViewTileProvider_OSM());
	session.setFile(QAD::userPath(QAD::ltConfig, "session_mapviewer"));
	session.addEntry(this);
	session.load();
	/*QVector<QPointF> g        = {QPointF(55.583055, 37.580008), QPointF(55.583055, 37.590008), QPointF(55.593055, 37.580008)};
	QVector<QPointF> p        = {QPointF(0, 0), QPointF(200, 0), QPointF(0, 100)};
	MapItemPolygon * pol      = new MapItemPolygon(QPolygonF(p));
	MapItemGeoPolyline * gpol = new MapItemGeoPolyline(QPolygonF(g));
	MapItemEllipse * ell      = new MapItemEllipse(QPointF(), 50, 50);
	MapItemImage * im         = new MapItemImage(QPixmap(":/icons/maps.png"));
	MapItemText * it          = new MapItemText(QString::fromUtf8("Это Ваня!"));
	im->setPosition({55.583055, 37.580008});
	im->setScale(0.2, 0.5);
	im->setAlignment(Qt::AlignRight | Qt::AlignTop);
	im->setCursor(Qt::PointingHandCursor);
	im->setInteracive(true);
	it->setPosition({55.583055, 37.580008});
	it->setBrush(QColor(127, 0, 0, 127));
	it->setPen(QColor(64, 255, 64));
	it->setFont(QFont("times", 18));
	it->setCursor(Qt::OpenHandCursor);
	it->setInteracive(true);
	pol->setPosition({55.583055, 37.580008});
	pol->setUnits(MapItemNonGeoGeometryBase::Pixels);
	gpol->setBrush(QColor(0, 0, 255, 64));
	gpol->setPen(QPen(QColor(64, 64, 255), 3));
	ell->setPosition({55.583055, 37.580008});
	ell->setStartAngle(-20);
	ell->setEndAngle(20);
	ell->setEllipse(QPointF(100, 0), 50, 50);
	ell->setInteracive(true);
	QTimer t;
	QObject::connect(&w, &MapView::itemClicked, [](MapItemBase * item) { qDebug() << "click" << item; });
	QObject::connect(&w, &MapView::itemEntered, [](MapItemBase * item) { qDebug() << "enter" << item; });
	QObject::connect(&w, &MapView::itemLeaved, [](MapItemBase * item) { qDebug() << "leave" << item; });

	QObject::connect(&t, &QTimer::timeout, [im, it, pol, ell]() {
		im->rotate(1);
		it->rotate(-0.1);
		// pol->rotate(0.2);
		ell->rotate(-0.2);
		static double t = 0.;
		t += 0.025;
		ell->setScale((sin(t) / 2. + 1.));
	});
	t.start(100);
	map->addItem(im);
	map->addItem(gpol);
	map->addItem(pol);
	map->addItem(it);
	map->addItem(ell);
	map->centerTo({55.583055, 37.580008});
	map->zoomTo(2);

	for (int i = 1; i <= 8; ++i) {
		double a  = i * 0.5;
		auto * ei = new MapItemEllipse();
		ei->setStartAngle(-a);
		ei->setEndAngle(a);
		ei->setEllipse(QRectF(-100, -100, 200, 200));
		ei->setUnits(MapItemNonGeoGeometryBase::Meters);
		ei->setPosition(55.5858, 37.5782 + i / 1000.);
		ei->setBrush(QColor(0, 0, 255, 64));
		ei->setPen({Qt::blue});
		map->addItem(ei);
	}*/
}


MainWindow::~MainWindow() {
	session.save();
	session.clear(true);
}


void MainWindow::changeEvent(QEvent * e) {
	QMainWindow::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange: retranslateUi(this); break;
	default: break;
	}
}


void MainWindow::loadingSession(QPIConfig & conf) {
	map->setCenter(conf.getValue("center", map->center()).toPointF());
	map->setZoom(conf.getValue("zoom", map->getZoom()).toDouble());
}


void MainWindow::savingSession(QPIConfig & conf) {
	conf.setValue("center", map->center());
	conf.setValue("zoom", map->getZoom());
}


void MainWindow::on_map_mapClicked(QPointF c) {
	connect(OSMGeocoding::queue(c), &OSMGeocodingResult::ready, [this](OSMGeocodingResult * res) {
		labelLocation->setText(res->displayName().trimmed());
	});
}


void MainWindow::on_buttonDownload_clicked() {
	static QString dir; // = map->cachePath();
	auto d = QFileDialog::getExistingDirectory(nullptr, tr("Select directory"), dir);
	if (d.isEmpty()) return;
	dir       = d;
	bool ok   = false;
	int maxzl = map->getMaximumZoomLevel();
	int curzl = map->getCurrentZoomLevel();
	int tzl   = QInputDialog::getInt(nullptr,
								   windowTitle(),
								   tr("Select maximum zoom level:"),
								   qMin(maxzl, curzl + 3),
								   qMin(maxzl, curzl + 1),
								   maxzl,
								   1,
								   &ok);
	if (!ok) return;
	auto prevcd = map->cachePath();
	map->setCachePath(dir);
	map->downloadCurrentView(tzl);
	map->setCachePath(prevcd);
}
