#ifndef WIFISENSORANDROID_H
#define WIFISENSORANDROID_H


#ifdef ANDROID

#include <QAndroidJniObject>

#include "../../misc/Debug.h"
#include "../WiFiSensor.h"

#include <Indoor/misc/Debug.h>

class WiFiSensorAndroid : public WiFiSensor {

private:

	/** hidden ctor. use singleton! */
	WiFiSensorAndroid() {;}

	bool started = false;

public:

	/** singleton access */
	static WiFiSensorAndroid& get() {
		static WiFiSensorAndroid wifi;
		return wifi;
	}

	void start() override {

		// do NOT start twice!
		if (started) {return;}
		started = true;

		// start scanning
		int res = QAndroidJniObject::callStaticMethod<int>("indoor/java/WiFi", "start", "()I");
		if (res != 1337) {throw Exception("error while starting WiFi");}

	}

	void stop() override {
		throw "todo";
	}

	bool isRunning() const override {
		return started;
	}

	/**
	 * called from WiFi.java
	 * handle the given incoming scan result
	 * just a bit curious, thus std::string instead of std::string&
	*/
	void handle(const std::string data) {

		// to-be-constructed sensor data
		WiFiMeasurements sensorData;

		// tag all scan-entries with the current app runtime
		const Timestamp curTS = Timestamp::fromRunningTime();

		// parse each mac->rssi entry
		for (int i = 0; i < (int)data.length(); i += 17+1+2) {
			const std::string bssid = data.substr(i, 17);
			const int8_t rssi = data[i+17];
			const int8_t pad1 = data[i+18];
			const int8_t pad2 = data[i+19];
			if (pad1 != 0 || pad2 != 0) {Debug::error("padding error within WiFi scan result");}
			sensorData.entries.push_back(WiFiMeasurement(AccessPoint(bssid), rssi, curTS));
		}

		// call listeners
		informListeners(sensorData);

		// interval debug
//		static Timestamp lastTS;
//		const Timestamp diff = curTS - lastTS;
//		Log::add("wifi", std::to_string(diff.ms()));
//		if (diff.ms() > 650) {
//			Log::add("wifi", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//		}
//		lastTS = curTS;


	}

};




#endif

#endif // WIFISENSORANDROID_H
