/// © MiroZ 2024

#include "App.h"
#include "Settings.h"
#include <WiFi.h>
#include "ReaderWriter.h"

#include "Ble.h"

static const char * TAG = "ble";

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

Ble::Ble(App & app) : m_app(app)
{
	m_rw = new ReaderWriter(512);
}

void Ble::start()
{
	ESP_LOGW(TAG, "Starting BLE...");

	uint8_t wifi_mac[8];
	esp_read_mac(wifi_mac, ESP_MAC_WIFI_STA);

	sprintf(m_name, "WP_%u_%02x%02x%02x", SETTINGS.device.id, wifi_mac[3], wifi_mac[4], wifi_mac[5]);

	BLEDevice::init(m_name);

	assert(m_server = BLEDevice::createServer());
	m_server->setCallbacks(this);
	assert(m_service = m_server->createService(SERVICE_UUID));

	m_characteristic = m_service->createCharacteristic(CHARACTERISTIC_UUID, 
		BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);

    m_characteristic->addDescriptor(new BLE2902());
    m_characteristic->setCallbacks(this);
    m_service->start();

    assert(m_advertising = m_server->getAdvertising());
    m_advertising->addServiceUUID(SERVICE_UUID);
    m_advertising->start();		
}

void Ble::onConnect(BLEServer* pServer)
{
	uint16_t id = pServer->getConnId();
	ESP_LOGI(TAG, "%d connected", id);
}

void Ble::onDisconnect(BLEServer* pServer)
{
	uint16_t id = pServer->getConnId();
	ESP_LOGI(TAG, "%d disconnected", id);
	m_advertising->start();
}

void Ble::onRead(BLECharacteristic *pCharacteristic)
{
	int a = 1234;
	pCharacteristic->setValue(a);
	ESP_LOGI(TAG, "onRead hello");
}

void Ble::onWrite(BLECharacteristic *pCharacteristic)
{
	uint32_t len = pCharacteristic->getLength();
	uint8_t * data = pCharacteristic->getData();
	data[len] = 0;

	Parser p((char *)data, "|");
	char buffer[80];
	p.getElementAt(0, buffer, sizeof(buffer));

	ESP_LOGI(TAG, "command '%s'", buffer);

	if(buffer[0] == 'w')
	{
		ESP_LOGI(TAG, "Scanning wifi networks...");

		int num_networks = WiFi.scanNetworks(false, false, false, 0);

		m_rw->reset();
		m_rw->appendf("w|%d|", num_networks);
		for(int n = 0; n < num_networks; n++)
		{
			m_rw->append(WiFi.SSID(n).c_str());
			m_rw->append(",");
			m_rw->appendf("%d", WiFi.RSSI(n));
			if(n < num_networks-1)
				m_rw->append("|");
		}
		ESP_LOGI(TAG, "'%s'", m_rw->getBuffer());
		m_characteristic->setValue(m_rw->getBuffer());
		m_characteristic->notify();
	}
	else if(buffer[0] == 'd')
	{
		SETTINGS.wifi.num = 0;
		SETTINGS_SAVE;
		esp_restart();
	}
}
