#ifndef WIFICALIBTOOL_H
#define WIFICALIBTOOL_H


#include <Indoor/floorplan/v2/Floorplan.h>
#include "Renderable2D.h"

#include "../../../Settings.h"
#include "HasSelectableNodes.h"

#include <QDialog>
#include <QPushButton>
#include "../../../tools/calibration/WiFiCalibrationDataModel.h"
#include "../../../tools/calibration/WiFiCalibrationScanDialog.h"

#include <QGridLayout>
#include <QLabel>
#include "../ui/UIHelper.h"

#include "../../../sensors/SensorFactory.h"

struct WiFiCalibPoint {
	std::string name;		// title
	Point3 pos_m;			// map position + smartphone height
	Point2 pos_px;			// screen position
	WiFiCalibPoint(const std::string& name, const Point3 pos_m, const Point2 pos_px) : name(name), pos_m(pos_m), pos_px(pos_px) {;}
	WiFiCalibPoint() {;}
};

/**
 * helper for wifi calibration
 */
class WiFiCalibTool : public Renderable2D {

private:

	WiFiCalibrationDataModel* mdl;
	Floorplan::IndoorMap* map;

	std::vector<WiFiCalibPoint> currentlyVisible;
	WiFiCalibPoint currentlySelected;


public:

	/** ctor */
	WiFiCalibTool(WiFiCalibrationDataModel* mdl, Floorplan::IndoorMap* map) : mdl(mdl), map(map) {

	}

	virtual void selectNode(const int idx) {
		currentlySelected = currentlyVisible[idx];
		showCalib(currentlySelected);
	}

	/** get all selectable caliration nodes */
	virtual std::vector<Point2> getNodes() const {
		std::vector<Point2> pts;
		for (const WiFiCalibPoint& cp : currentlyVisible) {pts.push_back(cp.pos_px);}
		return pts;
	}

protected:

	void doRender(QPainter& qp, const Scaler2D& s, const RenderParams2D& r) override {

		currentlyVisible.clear();
		const QFont font("Arial", 10);
		qp.setFont(font);

		for (const Floorplan::Floor* floor : map->floors) {
			for (const Floorplan::Beacon* beacon : floor->beacons) {

				const Point3 p = beacon->pos + Point3(0,0,floor->atHeight) + Point3(0,0,Settings::smartphoneAboveGround);
				const Point2 pt = s.mapToScreen(p.xy());

				if (floor->atHeight < r.clip.belowHeight_m) {continue;}
				if (floor->atHeight > r.clip.aboveHeight_m) {continue;}

				const WiFiCalibPoint cp(beacon->name, p, pt);
				currentlyVisible.push_back(cp);

				const WiFiFingerprint& fp = mdl->getFingerprint(cp.pos_m);
				const QString txt1(beacon->name.c_str());
				const QString txt2 = QString::number(fp.measurements.entries.size());
				qp.setPen(Qt::black);

				if (currentlySelected.name == cp.name) {
					qp.setBrush(Qt::blue);
				} else {
					qp.setBrush(Qt::NoBrush);
				}

				//FONT SIZE??


				int s = 20;
				qp.drawEllipse(pt.x-s, pt.y-s, s*2, s*2);
				qp.drawText(pt.x+s*2, pt.y-s, txt1);
				qp.drawText(pt.x+s*2, pt.y+s, txt2);

			}
		}

	}




private:



	void showCalib(const WiFiCalibPoint& cp) {

		// get (or create an empty one) the fingerprint for this location
		WiFiFingerprint& fp = mdl->getFingerprint(cp.pos_m);

		// edit it (blocking!)
		WiFiCalibrationScanDialog::get(fp);

		// save the model
		mdl->save();

	}

};

#endif // WIFICALIBTOOL_H
