///
/// © MiroZ 2024
///
/// Created on: Apr 17, 2019
/// Modified: 2024
///

#ifndef __PROVISIONSOFTAP_H__
#define __PROVISIONSOFTAP_H__

#include <ESPAsyncWebServer.h>
#include <DNSServer.h>
#include <list>
#include "ReaderWriter.h"
#include "Settings.h"

class ProvisionSoftAP
{
private:
	DNSServer m_dnsServer;
	AsyncWebServer * m_webServer;
	AsyncWebSocket * m_webSocket;
	std::list<int> m_clients;
	bool m_startWifiScan = false;
	bool m_tryConnect = false;

	ReaderWriter * m_rwriter = nullptr;

private:
	char m_ssid[32] = {0};
	char m_pwd[32] = {0};

private:
	void parseWebsocketCommand(char *data, size_t len);
	void tryConnect();

	// callbacks
	void wifiEvent(arduino_event_id_t event, arduino_event_info_t info);
	void websocketEvent(AsyncWebSocket * server, AsyncWebSocketClient * client,
	        AwsEventType type, void * arg, uint8_t *data, size_t len);
	void handlePortal(AsyncWebServerRequest* request);
	void handleLogo(AsyncWebServerRequest *request);
	void waitBufferEmpty();

public:
	void start(const char * ssid, const char * password);
	void start();

	ProvisionSoftAP(int port = 80);
	virtual ~ProvisionSoftAP();
};

#endif /* __PROVISIONSOFTAP_H__ */
