#ifndef CALIBDIALOG_H
#define CALIBDIALOG_H

#include <QWidget>
#include <QProgressBar>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QDialog>

#include "../sensors/SensorFactory.h"
#include "../tools/calibration/WiFiCalibrationDataModel.h"



/**
 * show a dialog to perform a WiFiScan
 */
class WiFiCalibrationScanDialog : public QObject, public SensorListener<WiFiMeasurements> {

	Q_OBJECT

private:

	QDialog* dlg = new QDialog();
	QLabel* lblStats;
	QLabel* lblPoint;
	QProgressBar* barProg;

	struct Scan {
		const int numRecords = 30;
		int recordsDone = 0;
	} scan;

	/** the measurements model to fill with scan-entries */
	WiFiFingerprint& model;

public:

	static void get(WiFiFingerprint& model) {
		WiFiCalibrationScanDialog dlg(model);
		dlg.show();
	}

private:

	/** ctor */
	WiFiCalibrationScanDialog(WiFiFingerprint& model);

	void show() {
		refresh();
		dlg->exec();
	}

	void close() {
		stopRecord();
		dlg->close();
	}

	void save() {
		//mdl.save();;
	}

	Q_INVOKABLE void refresh() {
		lblPoint->setText(QString(model.pos_m.asString().c_str()));
		lblStats->setText( QString::number(model.measurements.entries.size()) + " RSSI measurements\n" + QString::number(scan.recordsDone) + " scans");
		barProg->setValue(scan.recordsDone);
		barProg->setMaximum(scan.numRecords);
	}

	void clear() {
		model.measurements.entries.clear();
		refresh();
	}


	void startRecord() {
		scan.recordsDone = 0;
		SensorFactory::get().getWiFi().addListener(this);
		if (!SensorFactory::get().getWiFi().isRunning()) {
			SensorFactory::get().getWiFi().start();
		}
	}

	void stopRecord() {
		SensorFactory::get().getWiFi().removeListener(this);
	}

	virtual void onSensorData(Sensor<WiFiMeasurements>* sensor, const Timestamp ts, const WiFiMeasurements& data) override {
		(void) sensor;
		(void) ts;
		++scan.recordsDone;
		if (scan.recordsDone >= scan.numRecords) {stopRecord();}
		model.measurements.entries.insert(model.measurements.entries.end(), data.entries.begin(), data.entries.end());
		QMetaObject::invokeMethod(this, "refresh", Qt::QueuedConnection);
	}


};


#endif // CALIBDIALOG_H
